Skip to main content
 首页 » 编程设计

python之如何在scrapy下载器中间件中获取响应体

2024年10月01日6mfrbuaa

如果在页面上找不到某些 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中注册:

DOWNLOADER_MIDDLEWARES = { 
    'myproject.middlewares.ManualRetryMiddleware': 650, 
    'scrapy.downloadermiddlewares.retry.RetryMiddleware': None, 
} 

当我运行蜘蛛时,我得到

AttributeError: 'Response' object has no attribute 'xpath' 

我尝试手动创建选择器并在其上运行 xpath...但是响应没有 text 属性并且 response.body 是字节,而不是 str...

那么如何在中间件中查看页面内容呢?某些页面可能不包含我需要的详细信息,因此我希望稍后再试一次。

请您参考如下方法:

response不包含xpath方法的原因是下载器中间件的process_response方法中的response参数类型为 scrapy.http.Response , 请参阅 documentation .只有scrapy.http.TextResponse (和 scrapy.http.HtmlResponse )确实有 xpath 方法。所以在使用 xpath 之前,从 response 创建 HtmlResponse 对象。你类(class)的相应部分将变成:

... 
new_response = scrapy.http.HtmlResponse(response.url, body=response.body) 
if new_response.xpath(xpath).extract(): 
    found = True 
    break 
...