首页 > 解决方案 > 如何使用不同的输入多次运行蜘蛛

问题描述

我正在尝试从不同网站上抓取有关某些产品的信息。这是我的程序的结构:

product_list = [iPad, iPhone, AirPods, ...]

def spider_tmall:
    self.driver.find_element_by_id('searchKeywords').send_keys(inputlist[a])

# ...


def spider_jd:
    self.driver.find_element_by_id('searchKeywords').send_keys(inputlist[a])

# ...

if __name__ == '__main__':

    for a in range(len(inputlist)):
        process = CrawlerProcess(settings={
            "FEEDS": {
                "itemtmall.csv": {"format": "csv",
                                  'fields': ['product_name_tmall', 'product_price_tmall', 'product_discount_tmall'], },
                "itemjd.csv": {"format": "csv",
                               'fields': ['product_name_jd', 'product_price_jd', 'product_discount_jd'], },
        })

        process.crawl(tmallSpider)
        process.crawl(jdSpider)
        process.start()

基本上,我想为product_list. 现在,我的程序只运行一次所有蜘蛛(在这种情况下,它为 iPad 完成了这项工作)然后出现ReactorNotRestartable错误并且程序终止。有人知道如何解决吗?此外,我的总体目标是多次运行蜘蛛,输入不一定是列表。它可以是 CSV 文件或其他文件。任何建议将不胜感激!

标签: pythonseleniumweb-scrapingscrapyweb-crawler

解决方案


当你调用process.start()Scrapy时CrawlerProcess,将启动一个 Twisted reactor,默认情况下,当爬虫完成时它会停止并且不应该重新启动。您可以尝试的一种可能的解决方案是将stop_after_crawl 参数设置为执行False

 process.start(stop_after_crawl=False)

这将防止反应堆停止,绕过重启问题。虽然我不能说它不会进一步导致其他问题,所以你应该测试它以确定。

文档中还有一个在同一进程中运行多个蜘蛛的示例,其中一个主动运行/停止反应器,但它使用CrawlerRunner而不是CrawlerProcess.

最后,如果上面的解决方案没有帮助,我建议尝试这个:

if __name__ == '__main__':

    process = CrawlerProcess(settings={
        "FEEDS": {
            "itemtmall.csv": {"format": "csv",
                              'fields': ['product_name_tmall', 'product_price_tmall', 'product_discount_tmall'], },
            "itemjd.csv": {"format": "csv",
                           'fields': ['product_name_jd', 'product_price_jd', 'product_discount_jd'], },
    })
    for a in range(len(inputlist)):
        process.crawl(tmallSpider)
        process.crawl(jdSpider)
    process.start()

这里的重点是该过程只在循环外启动一次,并且CrawlerProcess 实例化也在循环外,否则每次迭代都会覆盖之前的CrawlerProcess.


推荐阅读