Scrapy框架启动多个爬虫的方法

有的时候在抓取过程中可能会出现同一个网站相同数据在不同url里有不同爬取方法的情况,所以这个时候需要编写多个爬虫,最开始是使用cmdline.execute(“scrapy crawl spider1”.split()) 启动爬虫,但发现用这种方法执行多个最后真正抓取的只有第二个。

from scrapy import cmdline

cmdline.execute("scrapy crawl spider1".split())
cmdline.execute("scrapy crawl spider2".split())  # 只会执行后面这一个

此方法行不通,后面采用了自定义scrapy命令解决这个问题,下面放代码和步骤:

  1. 创建commands目录
  2. 在commands下面添加一个文件crawlall.py 和 init.py文件,这一步貌似不能省略
    在这里插入图片描述
    和spider目录同级
  3. 在crawlall.py里面增加代码:(这里主要通过修改scrapy的crawl命令来完成同时执行spider的效果。crawl的源码可以在此查看:https://github.com/scrapy/scrapy/blob/master/scrapy/commands/crawl.py)
from scrapy.commands import ScrapyCommand
from scrapy.utils.project import get_project_settings


class Command(ScrapyCommand):
    requires_project = True

    def syntax(self):
        return '[options]'

    def short_desc(self):
        return 'Runs all of the spiders'

    def run(self, args, opts):
        spider_list = self.crawler_process.spiders.list()
        for name in spider_list:
            self.crawler_process.crawl(name, **opts.__dict__)
        self.crawler_process.start()
  1. 在settings里面添加配置
COMMANDS_MODULE = 'UGaming.commands'   # 自己的爬虫名称
  1. 运行命令scrapy crawlall 或者新建启动文件:
cmdline.execute("scrapy crawlall".split()) 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值