python - Scrapy 蜘蛛 : Restart spider when finishes

标签 python python-2.7 web-scraping scrapy

如果关闭的原因是因为我的互联网连接(夜间互联网中断 5 分钟),我正在尝试让我的 Scrapy 蜘蛛再次启动。当互联网出现故障时,蜘蛛会在 5 次尝试后关闭。

我试图在我的蜘蛛定义中使用这个函数,试图在关闭时重新启动蜘蛛:

def handle_spider_closed(spider, reason):
    relaunch = False
    for key in spider.crawler.stats._stats.keys():
        if 'DNSLookupError' in key:
            relaunch = True
            break

    if relaunch:
        spider = mySpider()
        settings = get_project_settings()
        crawlerProcess = CrawlerProcess(settings)
        crawlerProcess.configure()
        crawlerProcess.crawl(spider)
        spider.crawler.queue.append_spider(another_spider)

我尝试了很多事情,比如重新实例化一个蜘蛛,但得到了错误 Reactor is already running 或类似的东西。

我考虑过从脚本中执行爬虫,当爬虫完成后再次调用它,但都没有用,因为 react 器仍在使用中。

  • 我的目的是在蜘蛛关闭后重置它(蜘蛛关闭是因为它失去了互联网连接)

有谁知道一个好的简单方法来做到这一点?

最佳答案

我找到了解决问题的方法!我想做什么?

  • 在失败或关闭时处理蜘蛛
  • 尝试在关闭时重新执行蜘蛛

我通过这样处理蜘蛛的错误来管理:

import time

class mySpider(scrapy.Spider):
    name = "myspider"
    allowed_domains = ["google.com"]
    start_urls = [
        "http://www.google.com",
    ]

    def handle_error(self, failure):
        self.log("Error Handle: %s" % failure.request)
        self.log("Sleeping 60 seconds")
        time.sleep(60)
        url = 'http://www.google.com'
        yield scrapy.Request(url, self.parse, errback=self.handle_error, dont_filter=True)

    def start_requests(self):
        url = 'http://www.google.com'
        yield scrapy.Request(url, self.parse, errback=self.handle_error)
  • 我使用 dont_filter=True 让 Spider 允许复制一个请求,只有当它遇到错误时。
  • errback=self.handle_error 让 Spider 通过自定义的 handle_error 函数

关于python - Scrapy 蜘蛛 : Restart spider when finishes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28987240/

相关文章:

python - 以单独的名称安装包的分支

python-2.7 - 通过数据包注入(inject)进行 HTTP 响应欺骗

python - Beautifulsoup 无法找到名称中带有连字符的类

通过 cmd 打开时 python.exe 已停止工作

python - 将一个元素添加到 pandas dataframe 中的数组末尾

Python:从字符串中检测单词并找到它的位置

python - 为什么我不能调用container.findAll ("h3",{"class":"name"})?

python - 复制生成器

python-3.x - Selenium WebDriverWait 在网络抓取时在 Python 上返回错误

javascript - 如何触发自动点击警报 btn ok 以继续加载目标 url?