1、使用CrawProcess實現(xiàn)
https://doc.scrapy.org/en/latest/topics/practices.html
2、修改craw源碼+自定義命令的方式實現(xiàn)
(1)我們打開scrapy.commands.crawl.py 文件可以看到:
1
2
3
4
5
6
7
8
9
|
def run( self , args, opts): if len (args) < 1 : raise UsageError() elif len (args) > 1 : raise UsageError( "running 'scrapy crawl' with more than one spider is no longer supported" ) spname = args[ 0 ] self .crawler_process.crawl(spname, * * opts.spargs) self .crawler_process.start() |
這是crawl.py 文件中的run() 方法,在此可以指定運行哪個爬蟲,要運行所有的爬蟲,則需要更改這個方法。
run() 方法中通過crawler_process.crawl(spname, **opts.spargs) 實現(xiàn)了爬蟲文件的運行,spname代表爬蟲名。要運行多個爬蟲文件,首先要獲取所有的爬蟲文件,可以通過crawler_process.spider_loader.list() 實現(xiàn)。
(2)實現(xiàn)過程:
a、在spider目錄的同級目錄下創(chuàng)建存放源代碼的文件夾mycmd,并在該目錄下創(chuàng)建文件mycrawl.py;
b、將crawl.py 中的代碼復制到mycrawl.py 文件中,然后進行修改:
1
2
3
4
5
6
7
8
9
|
#修改后的run() 方法 def run( self , args, opts): #獲取爬蟲列表 spd_loader_list = self .crawler_process.spider_loader. list () #遍歷各爬蟲 for spname in spd_loader_list or args: self .crawler_process.crawl(spname, * * opts.spargs) print ( "此時啟動的爬蟲:" + spname) self .crawler_process.start() |
同時可以修改:
1
2
|
def short_desc( self ): return "Run all spider" |
c、在mycmd文件夾下添加一個初始化文件__init__.py,在項目配置文件(setting.py)中添加格式為“COMMANDS_MODULES='項目核心目錄.自定義命令源碼目錄'”的配置;
例如:COMMANDS_MODULE = 'firstpjt.mycmd'
隨后通過命令“scrapy -h”,可以查看到我們添加的命令mycrawl
這樣,我們就可以同時啟動多個爬蟲文件了,使用命令:
1
|
scrapy mycrawl - - nolog |
到此這篇關于Scrapy爬蟲文件批量運行的實現(xiàn)的文章就介紹到這了,更多相關Scrapy 批量運行內(nèi)容請搜索服務器之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/SteveForever/article/details/81607018