重定向問題
在使用python爬蟲的過程中難免會遇到很多301,302的問題。他們出現(xiàn)時,很大程度的影響到我們的爬蟲速度和信息的準確性。下面針對不同的模塊給出不同的解決方案。
使用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的意思是,如果已經(jīng)爬取過得url,也就是沒有出現(xiàn)問題的url,自然而然出現(xiàn)問題的url將會再次被傳遞,這樣也就解決了重定向問題。