美文网首页
python爬虫的重定向问题(301,302)

python爬虫的重定向问题(301,302)

作者: Py_Explorer | 来源:发表于2018-02-01 16:02 被阅读0次

    重定向问题

    在使用python爬虫的过程中难免会遇到很多301,302的问题。他们出现时,很大程度的影响到我们的爬虫速度和信息的准确性。下面针对不同的模块给出不同的解决方案。

    使用requests模块爬虫

    使用requests模块遇到301和302问题时,

    def yunsite():
        'url'
        headers = {'Accept':     'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
               'Accept-Encoding': 'gzip, deflate, sdch, br',
               'Accept-Language': 'zh-CN,zh;q=0.8',
               'Connection': 'keep-alive',
               'Host': 'pan.baidu.com',
               'Upgrade-Insecure-Requests': '1',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
    
        url = 'https://pan.baidu.com/s/1c0rjnbi'
        html = requests.get(url, headers=headers, allow_redirects=False)
        return html.headers['Location']
    

    allow_redirects=False的意义为拒绝默认的301/302重定向从而可以通过html.headers[‘Location’]拿到重定向的URL。
    使用scrapy模块进行爬虫的时候遇到301很302问题。

     yield scrapy.Request(url,meta={
                        'title':tit,
                        'describe':describ,
                        'home_url':home_url,
                        'number':number
                    },callback=self.parse_item, dont_filter=True)
    

    这是在yield里面加上dont_filter=True,解决了这个问题,dont_filter的意思是,如果已经爬取过得url,也就是没有出现问题的url,自然而然出现问题的url将会再次被传递,这样也就解决了重定向问题。

    相关文章

      网友评论

          本文标题:python爬虫的重定向问题(301,302)

          本文链接:https://www.haomeiwen.com/subject/zvidzxtx.html