當我們利用Python scrapy框架寫完腳本后,腳本已經可以穩定的進行數據的爬取,但是每次需要手動的執行,太麻煩,如果能自動運行,在自動關閉那就好了,經過小編研究,完全是可以實現的,今天小編介紹2種方案來解決這個問題
由於scrapy框架本身沒有提供這樣的功能,所以小編采用了linux 中crontab的方式進行定時任務的爬取
方案一:
編寫shell腳本文件cron.sh
#! /bin/bash export PATH=$PATH:/usr/local/bin cd /home/python3/scrapydemo/Ak17/AK17/spiders nohup scrapy crawl novel >> novel.log 2>&1 &
終端執行命令crontab -e,規定crontab要執行的命令和要執行的時間頻率,這里我需要每5分鍾就執行scrapy crawl novel 這條爬取命令:
# daemon's notion of time and timezones. # # Output of the crontab jobs (including errors) is sent through # email to the user the crontab file belongs to (unless redirected). # # For example, you can run a backup of all your user accounts # at 5 a.m every week with: # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ # # For more information see the manual pages of crontab(5) and cron(8) # # m h dom mon dow command */5 * * * * sh /home/python3/scrapydemo/Ak17/cron.sh
* 如果報錯No MTA installed, discarding output,可以重定向到/dev/null,這個文件是一個無底洞,無法打開
例如:*/5 * * * * sh /home/python3/scrapydemo/Ak17/cron.sh > /dev/null 2>&1
如果輸入crontab -e后顯示如下,直接隨便輸入一個數字即可,小編這里輸入的2

編輯好后,執行命令打開crontab的日志,默認linux系統是不開啟的,將cron.*這一行前的注釋打開:
vi /etc/rsyslog.d/50-default.conf

重啟系統日志服務
sudo service rsyslog restart
最后就可以使用tail –f /var/log/cron.log查看crontab的日志了
方案二:
和方案一唯一的區別是沒有日志的輸出信息,直接修改定時任務即可
終端執行命令crontab -e,規定crontab要執行的命令和要執行的時間頻率
# daemon's notion of time and timezones. # # Output of the crontab jobs (including errors) is sent through # email to the user the crontab file belongs to (unless redirected). # # For example, you can run a backup of all your user accounts # at 5 a.m every week with: # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ # # For more information see the manual pages of crontab(5) and cron(8) # # m h dom mon dow command */5 * * * * cd /home/python3/scrapydemo/Ak17/AK17/spiders && /usr/local/bin/scrapy crawl novel
關閉定時任務:
scrapy的setting中添加一個配置項
CLOSESPIDER_TIMEOUT = 82800 # 23小時后結束爬蟲
解釋一下
CLOSESPIDER_TIMEOUT
默認值: 0
一個整數值,單位為秒。如果一個spider在指定的秒數后仍在運行, 它將以 closespider_timeout 的原因被自動關閉。 如果值設置為0(或者沒有設置),spiders不會因為超時而關閉。
順便說一下crontab的常見格式:
每分鍾執行 */1 * * * * 每小時執行 0 * * * * 每天執行 0 0 * * * 每周執行 0 0 * * 0 每月執行 0 0 1 * * 每年執行 0 0 1 1 *
