def demo(): headers = {'Accept':'xxxx', 'Accept-Encoding':'xxxx', 'Accept-Language':'xxxx', 'Connection':'xxxx', 'Host':'xxxx', 'Upgrade-Insecure-Requests':'x', '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:xxxxx.com' html = requests.get(url, headers=headers, allow_redirects=False) return html.headers['Location']
allow_redirects=False的意義為拒絕默認的301/302重定向從而可以通過html.headers[‘Location’]拿到重定向的URL。
這是scrapy中解決問題方法1:
在yield里面加上dont_filter=True,解決了這個問題,dont_filter的意思是,如果已經爬取過得url,也就是沒有出現問題的url,
自然而然出現問題的url將會再次被傳遞,這樣也就解決了重定向問題。
yield scrapy.Request(url=listUrl[i],callback=self.get_content,meta={'item':item},method='GET',dont_filter=True)
有時候爬取圖片獲取不到,返回302,我們可以在配置文件settings.py
里面修改重定向:如下:
值加這一行代碼:
MEDIA_ALLOW_REDIRECTS =True
ITEM_PIPELINES = { 'scrapy.pipelines.images.ImagesPipeline':1, 'Moni.pipelines.MoniPipeline': 300, } MEDIA_ALLOW_REDIRECTS =True # 只有這一行代碼,其他的是為了方便查找,加上這一行基本上就能解決了 IMAGES_STORE = './images'