python - 如何使用不同的输入多次运行蜘蛛
问题描述
我正在尝试从不同网站上抓取有关某些产品的信息。这是我的程序的结构:
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 文件或其他文件。任何建议将不胜感激!
解决方案
当你调用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
.
推荐阅读
- javascript - 如何在 Select 标签中放置 2000 多个项目?
- html - 为 CSS 动画添加悬停效果
- c# - 如何在c#中反序列化来自http发布的json文件的数据
- javascript - 为什么 classList.contain() 总是返回 false?
- reactjs - 将类组件函数转换为函数组件函数
- r - 当统计测试使用二进制变量时,将 p 值输出保存到数据帧
- javascript - 为什么 document.addEventListener('DOMContentLoaded', Store.DisplayBooks) 不起作用
- python - 尝试使用来自 csv 文件的 4 个输入来模拟一个 FMU 时出错
- google-cloud-platform - 谷歌数据融合如何使用条件插件触发分支?
- java - 匹配括号内的所有逗号使用正则表达式