Scrapy:收集重试消息

时间:2015-01-06 06:51:46

标签: python scrapy scrapy-spider

爬行程序有一个格式化次数,如文档here所示。达到此目的后,我得到了类似于以下内容的错误:

Gave up retrying <GET https:/foo/bar/123> (failed 3 times)

我相信邮件是由代码here生成的。

但是,我想对放弃做一些总结。具体来说,我想知道是否有可能:

  1. 提取网址的123部分(ID)并将这些ID正确地写入单独的文件中。
  2. 访问原始meta中的request信息。 This documentation可能会有帮助。

1 个答案:

答案 0 :(得分:5)

您可以继承scrapy.contrib.downloadermiddleware.retry.RetryMiddleware并覆盖_retry(),以便根据请求执行您想要的任何操作。

from scrapy.contrib.downloadermiddleware.retry import RetryMiddleware
from scrapy import log

class CustomRetryMiddleware(RetryMiddleware):

    def _retry(self, request, reason, spider):
        retries = request.meta.get('retry_times', 0) + 1

        if retries <= self.max_retry_times:
            log.msg(format="Retrying %(request)s (failed %(retries)d times): %(reason)s",
                    level=log.DEBUG, spider=spider, request=request, retries=retries, reason=reason)
            retryreq = request.copy()
            retryreq.meta['retry_times'] = retries
            retryreq.dont_filter = True
            retryreq.priority = request.priority + self.priority_adjust
            return retryreq
        else:
            # do something with the request: inspect request.meta, look at request.url...
            log.msg(format="Gave up retrying %(request)s (failed %(retries)d times): %(reason)s",
                    level=log.DEBUG, spider=spider, request=request, retries=retries, reason=reason)

然后,您需要在settings.py

中引用此自定义中间件组件
DOWNLOADER_MIDDLEWARES = {
    'scrapy.contrib.downloadermiddleware.retry.RetryMiddleware': None,
    'myproject.middlewares.CustomRetryMiddleware': 500,
}