scrapy 使用技巧
1、中间键等级相同的情况下,优先调用自定义中间件
关于重定向:
1、可以设置handle_httpstatus_list参数用以过滤需要重定向的响应码或直接设置不要重定向
class RedirectMiddleware(BaseRedirectMiddleware):
"""
Handle redirection of requests based on response status
and meta-refresh html tag.
"""
def process_response(self, request, response, spider):
if (request.meta.get('dont_redirect', False) or
response.status in getattr(spider, 'handle_httpstatus_list', []) or
response.status in request.meta.get('handle_httpstatus_list', []) or
request.meta.get('handle_httpstatus_all', False)):
return response
2、默认要重新请求的情况:
响应headers中要包含Location 且 响应码必须为301, 302, 303, 307, 308其中一个。
allowed_status = (301, 302, 303, 307, 308)
if 'Location' not in response.headers or response.status not in allowed_status:
return response