Scrapy:如何捕获下载错误并尝试再次下载

dab*_*205 6 python scrapy

在我的爬网过程中,某些页面因意外重定向而失败,并且未返回任何响应.如何捕获此类错误并使用原始URL重新安排请求,而不是使用重定向的URL?

在我问这里之前,我在Google上做了很多搜索.看起来有两种方法可以解决这个问题.一个是下载中间件中的catch异常,另一个是在spider的请求中处理errback中的下载异常.对于这两个问题,我有一些问题.

  • 对于方法1,我不知道如何将原始url传递给process_exception函数.下面是我尝试过的示例代码.
class ProxyMiddleware(object):

    def process_request(self, request, spider):
        request.meta['proxy'] = "http://192.168.10.10"
        log.msg('>>>> Proxy %s'%(request.meta['proxy'] if request.meta['proxy'] else ""), level=log.DEBUG)
    def process_exception(self, request, exception, spider):
        log_msg('Failed to request url %s with proxy %s with exception %s' % (request.url, proxy if proxy else 'nil', str(exception)))
        #retry again.
        return request
Run Code Online (Sandbox Code Playgroud)
  • 对于方法2,我不知道如何将外部参数传递给spider中的errback函数.我不知道如何从这个errback函数中检索原始url来重新安排请求.

    下面是我尝试使用方法2的示例:

class ProxytestSpider(Spider):

    name = "proxytest"
    allowed_domains = ["baidu.com"]
    start_urls = (
        'http://www.baidu.com/',
        )
    def make_requests_from_url(self, url):
        starturl = url
        request = Request(url, dont_filter=True,callback = self.parse, errback = self.download_errback)
        print "make requests"
        return request
    def parse(self, response):
        pass
        print "in parse function"        
    def download_errback(self, e):
        print type(e), repr(e)
        print repr(e.value)
        print "in downloaderror_callback"
Run Code Online (Sandbox Code Playgroud)

对此重新抓取问题的任何建议都非常感谢.提前致谢.

问候

小智 2

您可以将 lambda 作为 errback 传递:

request = Request(url, dont_filter=True,callback = self.parse, errback = lambda x: self.download_errback(x, url))
Run Code Online (Sandbox Code Playgroud)

这样你就可以访问 errback 函数中的 url:

def download_errback(self, e, url):
    print url
Run Code Online (Sandbox Code Playgroud)