Scrapy:在请求失败(例如404,500)时,如何请求另一个替代请求?

Zha*_*hou 7 python scrapy web-scraping http-status-code-404

我有scrapy的问题.在请求失败(例如404,500)时,如何请求另一个替代请求?如两个链接可以获取价格信息,一个失败,自动请求另一个.

Oma*_*hir 14

在请求中使用"errback", errback=self.error_handler 其中error_handler是一个函数(就像回调函数一样),在此函数中检查错误代码并进行替代请求.

请参阅scrapy文档中的errback:http://doc.scrapy.org/en/latest/topics/request-response.html


ale*_*cxe 7

只需设置handle_httpstatus_list = [404, 500]并检查方法中的状态代码即可parse.这是一个例子:

from scrapy.http import Request
from scrapy.spider import BaseSpider


class MySpider(BaseSpider):
    handle_httpstatus_list = [404, 500]
    name = "my_crawler"

    start_urls = ["http://github.com/illegal_username"]

    def parse(self, response):
        if response.status in self.handle_httpstatus_list:
            return Request(url="https://github.com/kennethreitz/", callback=self.after_404)

    def after_404(self, response):
        print response.url

        # parse the page and extract items
Run Code Online (Sandbox Code Playgroud)

另见:

希望有所帮助.