如果页面上没有找到某些xpath,我需要能够重试请求。所以我编写了这个中间件:
class ManualRetryMiddleware(RetryMiddleware):
def process_response(self, request, response, spider):
if not spider.retry_if_not_found:
return response
if not hasattr(response, 'text') and response.status != 200:
return super(ManualRetryMiddleware, self).process_response(request, response, spider)
found = False
for xpath in spider.retry_if_not_found:
if response.xpath(xpath).extract():
found = True
break
if not found:
return self._retry(request, "Didn't find anything useful", spider)
return response
并在settings.py
中注册:
当我跑蜘蛛的时候
AttributeError: 'Response' object has no attribute 'xpath'
我试图手动创建选择器并在其上运行xpath。。。但是响应没有text
属性,response.body
是字节,而不是str。。。在
那么如何在中间件中检查页面内容呢?有可能有些页面不包含我需要的详细信息,所以我想稍后再试一次。在
还要注意中间件的位置。它必须在
scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware
之前,否则,您可能会尝试解码压缩数据(这确实不起作用)。检查响应.标题要知道响应是否被压缩-Content-Encoding: gzip
。在response
不包含xpath
方法的原因是下载中间件的process_response
方法中的response
参数属于{a1}类型,参见documentation。只有^{xpath
方法。所以在使用xpath
之前,从response
创建{相关问题 更多 >
编程相关推荐