scrapy 运行多爬虫

自作多情 提交于 2020-01-19 05:20:13
背景:scrapy是支持多爬虫启动的,有两种方式.
你可以使用scrapy.crawler.CrawlerProcess这个类来运行你的spider,这个类会为你启动一个Twisted reactor,并能配置你的日志和shutdown处理器。所有的scrapy命令都使用这个类.
另外一个功能更强大的类是scrapy.crawler.CrawlerRunner,我用的就是这个,目前同时启动过7个爬虫,如果有文件读写操作,记得开启ulimit -n 2048.
多爬虫启动就是指同一进程启动多个爬虫.
import scrapy
from twisted.internet import reactor
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging

class MySpider1(scrapy.Spider):
    # Your first spider definition
    ...

class MySpider2(scrapy.Spider):
    # Your second spider definition
    ...

configure_logging()
runner = CrawlerRunner()
runner.crawl(MySpider1)
runner.crawl(MySpider2)
d = runner.join()
d.addBoth(lambda _: reactor.stop())

reactor.run() # the script will block here until all crawling jobs are finished

上述示例是scrapy cookbook给的示例,我觉得一般不会那么写,应该在一个循环里启动爬虫,因为在这个迭代里,你可以做很多事情,例如筛出报错的爬虫(加了测试的)话.

那怎么来合适的启动多爬虫呢?
我这里说下思路,我是这么做的,在spiders的__init__写一个类获取spiders里的所有爬虫类,在在run.py引用这个类,这样你就获得了所有爬虫,runner.crawl()传入的是爬虫的类对象,命名要规范如XXXSpider,没有Spider,可能会出错.然后在迭代里启动爬虫,这样做有哪些好处呢?可以加入测试模块、定时模块等等。
scrapy cookbook链接
scrapy官方文档链接

在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!