【问题标题】:How to run multiple spiders in the same process in Scrapy如何在 Scrapy 的同一进程中运行多个蜘蛛
【发布时间】:2014-04-10 18:09:07
【问题描述】:

我是 Python 和 Scrapy 的初学者。我刚刚创建了一个包含多个蜘蛛的 Scrapy 项目,当运行“scrapy crawl ..”时,它只运行第一个蜘蛛。

如何在同一个进程中运行所有蜘蛛?

提前致谢。

【问题讨论】:

  • 你需要运行同一个蜘蛛的多个实例还是一组不同的蜘蛛?
  • 我的项目文件夹“spiders”中有很多蜘蛛。 &我想一次性运行所有这些,而不是为每个运行“scrapy crawl”。另外我想知道是否有办法自动执行此任务,例如每小时运行一次爬网。谢谢

标签: python python-2.7 scrapy


【解决方案1】:

您将为文件中的每个蜘蛛命名name="youspidername"。当您使用scrapy crawl yourspidername 调用它时,它只会抓取该蜘蛛。您将不得不再次使用scrapy crawl youotherspidername 发出命令来运行另一个蜘蛛。

另一种方法是在同一命令中提及所有蜘蛛,例如scrapy crawl yourspidername,yourotherspidername,etc..(较新版本的scrapy不支持此方法)

【讨论】:

  • 嗨@Reddy 感谢您的回复。我已经尝试了您的第一种方法并且它正在工作,但实际上我需要使用一个命令运行所有蜘蛛。可能我需要编写一个新的 file.py 来运行每个蜘蛛或类似的东西,但我不知道具体如何!你是对的,另一种方法不起作用。
  • 很简单。只需将新类添加到您的 items.py 文件中,然后将它们导入以在您的蜘蛛中创建(定义)一个新的解析器。
【解决方案2】:

每个人,甚至是文档,都建议使用内部 API 编写一个“运行脚本”来控制多个蜘蛛的启动和停止。但是,除非您完全正确,否则这会带来很多警告(feedexports 不起作用,扭曲的反应堆没有停止或停止太快等)。

在我看来,我们有一个已知的工作和受支持的scrapy crawl x 命令,因此更简单的处理方法是使用 GNU Parallel 进行并行化。

安装后,每个核心运行(从外壳)一个scrapy spider,并假设您希望运行项目中的所有蜘蛛:

scrapy list | parallel --line-buffer scrapy crawl

如果您只有一个内核,您可以使用 GNU Parallel 的 --jobs 参数。例如,以下将每个核心运行 2 个 scrapy 作业:

scrapy list | parallel --jobs 200% --line-buffer scrapy crawl

【讨论】:

    【解决方案3】:

    默认情况下,当你运行时,Scrapy 会为每个进程运行一个蜘蛛 爬行爬行。但是,Scrapy 支持每个运行多个蜘蛛 使用内部 API 处理。

    欲了解更多信息,请点击此处: https://docs.scrapy.org/en/latest/topics/practices.html#running-multiple-spiders-in-the-same-process

    import scrapy
    from scrapy.crawler import CrawlerProcess
    
    class MySpider1(scrapy.Spider):
        # Your first spider definition
        ...
    
    class MySpider2(scrapy.Spider):
        # Your second spider definition
        ...
    
    process = CrawlerProcess()
    process.crawl(MySpider1)
    process.crawl(MySpider2)
    process.start() # the script will block here until all crawling jobs are finished
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多