《爬蟲筆記》初學爬蟲:入門進階(3)

這篇記錄一下如何部署scrapy 項目

這裏是在入門進階(2)的代碼基礎,把 scrapy 項目部署到服務器上,並執行啓動命令

一、 通過Xftp將項目丟到服務器的 /home 目錄下

 

二、 執行項目

1. 非調度執行

先在服務器的 /home 路徑下創建兩個文件夾 crawlerlogs

執行爬蟲(scrapy crawl test),並打印日誌(/home/logs/crawlerDemo.log),代碼如下:

cd /home/crawler/crawlerDemo && nohup scrapy crawl test > /home/logs/crawlerDemo.log 2>&1 &

2. 調度執行

同樣的,先在服務器的 /home 路徑下創建兩個文件夾 crawlerlogs

在入門進階(2)的代碼基礎,新建一個調度py文件,

調度py文件需要建在這一層級中,否則會出現意想不到的驚喜 ~ ~ ~

import logging
import schedule
import subprocess
import os

# 需要調度的爬蟲的name
spider_name = "test"

# 創建日誌組件
logger = logging.getLogger("consume_redis")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

def job():
    child = subprocess.Popen(["pgrep", "-f", spider_name], stdout=subprocess.PIPE, shell=False)
    logger.info(child)
    pid = child.communicate()[0].decode('utf-8')
    logger.info(pid)
    if not pid:
        shell = "cd /home/crawler && nohup scrapy crawl " + spider_name + " >/home/logs/" + spider_name + ".log 2>&1 &"
        os.system(shell)
        logger.info("爬蟲啓動成功")
    else:
        logger.info("該爬蟲已在服務器運行!")

# 首次執行方法
job()

# 定時調度器(分鐘)
#schedule.every(10).minutes.do(job)
schedule.every().day.at("08:00").do(job)

while True:
    schedule.run_pending()

使用了調度器以後,所以在Linux中執行項目的命令也會有所改變

執行爬蟲,並打印日誌,代碼如下:

cd /home/crawler/crawlerDemo/crawlerDemo && nohup python demoTaskSpider.py > /home/logs/demoTaskSpider.log 2>&1 &

日誌路徑(爬蟲輸出的日誌文件名以 爬蟲name 命名)

調度器日誌:/home/logs/demoTaskSpider.log

爬蟲日誌:/home/logs/爬蟲名.log

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章