【问题标题】:How to mark scrape failed because of 503 as error in Scrapy?如何将由于 503 导致的刮擦失败标记为 Scrapy 中的错误?
【发布时间】:2025-11-25 06:59:40
【问题描述】:

所以我在爬行时得到状态 503。它已重试,但随后被忽略。我希望它被标记为错误,而不是被忽略。该怎么做?

我更喜欢将它设置为settings.py,这样它就适用于我所有的蜘蛛。 handle_httpstatus_list 似乎只会影响一只蜘蛛。

【问题讨论】:

    标签: web-scraping scrapy scrapy-spider http-status-codes scrapy-settings


    【解决方案1】:

    最后,我覆盖了重试中间件,只是为了做一点小改动。我是这样设置的,每次爬虫放弃重试某个东西,不管状态码是什么,都会被标记为错误。

    似乎 Scrapy 不会将放弃重试视为错误。这对我来说很奇怪。

    如果有人想使用它,这就是中间件。不要忘记在settings.py上激活它

    from scrapy.downloadermiddlewares.retry import *
    
    class Retry500Middleware(RetryMiddleware):
    
        def _retry(self, request, reason, spider):
            retries = request.meta.get('retry_times', 0) + 1
    
            if retries <= self.max_retry_times:
                logger.debug("Retrying %(request)s (failed %(retries)d times): %(reason)s",
                             {'request': request, 'retries': retries, 'reason': reason},
                             extra={'spider': spider})
                retryreq = request.copy()
                retryreq.meta['retry_times'] = retries
                retryreq.dont_filter = True
                retryreq.priority = request.priority + self.priority_adjust
                return retryreq
            else:
                # This is the point where I update it. It used to be `logger.debug` instead of `logger.error`
                logger.error("Gave up retrying %(request)s (failed %(retries)d times): %(reason)s",
                             {'request': request, 'retries': retries, 'reason': reason},
                             extra={'spider': spider})
    

    【讨论】:

      【解决方案2】:

      您应该研究两个设置:

      RETRY_HTTP_CODES:

      默认值:[500、502、503、504、408]

      要重试哪些 HTTP 响应代码。总是会重试其他错误(DNS 查找问题、连接丢失等)。

      https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#retry-http-codes

      还有HTTPERROR_ALLOWED_CODES:

      默认值:[]

      传递此列表中包含的所有非 200 状态代码的响应。

      https://doc.scrapy.org/en/latest/topics/spider-middleware.html#std:setting-HTTPERROR_ALLOWED_CODES

      【讨论】:

      • 我试过HTTPERROR_ALLOWED_CODES = [503]。不工作。对不起
      最近更新 更多