在每次异常后,scrapy 指数退避以重新启动蜘蛛爬行

lol*_*ter 5 python scrapy web-scraping

我想要一个爬虫蜘蛛,它一直运行到完成,但可以在遇到异常时在中间启动和停止。

每次发生错误时,可能是这样的:

def parse_inner_page(self, response):
    if "Sorry, we just need to make sure you're not a robot" in response.body:
        # want to stop the spider here and have the entire spider
        # remember states of request and retry after 2 seconds, 
        # and if that fails, wait 2^2 seconds, 2^3 after that, etc...
        pass
Run Code Online (Sandbox Code Playgroud)

所以这需要:

  1. 一些外部状态的存储和更新nn等待2^秒)
  2. 能够从脚本中优雅地停止蜘蛛(见上文)
  3. 能够重新启动蜘蛛,包括所有失败的响应/请求,并让它们在爬行中的同一位置重新启动(深度、元数据等)。

这在scrapy中是可能的,编码这个的最佳方法是什么?

我认为答案是使用 scrapy jobs,并且我已经开始将 Python 脚本放在一起,如下所示:

import scrapy
from scrapy.crawler import CrawlerProcess

from myproject.spiders.mymodule import MySpider

#https://doc.scrapy.org/en/latest/topics/jobs.html

process = CrawlerProcess({'JOBDIR': './job'})
process.crawl(MySpider)
process.start()
Run Code Online (Sandbox Code Playgroud)

但是我应该有一个while循环吗?如何从爬行内部将信号发送process回外部,在那里我可以重新启动等?

如何从蜘蛛的功能之一中关闭蜘蛛 - 我是否需要模拟按 Ctrl+C?

import subprocess
import signal

process = subprocess.Popen(..)
process.send_signal(signal.SIGINT)
Run Code Online (Sandbox Code Playgroud)