scrapy——解决302重定向

 

在爬虫多次请求时,有些网站会出现反爬虫措施:将请求链接重定向到一个提示404的链接或者验证码链接等阻止爬虫的进行,如下为解决方案:

def start_requests(self):
        for i in self.start_urls:
            yield Request(i, meta={
                'dont_redirect': True,
                'handle_httpstatus_list': [302]
            }, callback=self.parse) 

# 'dont_redirect': True是禁止重定向
# Request.meta 中的 handle_httpstatus_list 键可以用来指定每个request所允许的response code。

 

此外:

根据 HTTP标准 ,返回值为200-300之间的值为成功的resonse。

如果想处理在这个范围之外的response,可以通过 spider的 handle_httpstatus_list 属性或HTTPERROR_ALLOWED_CODES 设置来指定spider能处理的response返回值。

例如,如果想要处理返回值为404的response可以这么做:

class MySpider(CrawlSpider):
  handle_httpstatus_list = [404]

  

 

posted @ 2019-07-02 14:27  lanston  阅读(8001)  评论(2编辑  收藏  举报