爬蟲遭遇重定向如何解決
阿新 • • 發佈:2018-12-14
錯誤記錄:
1.requests.exceptions.TooManyRedirects: Exceeded 30 redirects
錯誤提示是requests庫有太多的重定向:超過了30個重定向
解決辦法:
error_url = requests.get(news, headers=headers, allow_redirects=False) print(error_url.status_code) mypage = error_url.headers["Location"]
2.KeyError:
error_url.headers["Location"] #這裡報錯
dict[key]的方法取值,如果鍵key不存在,則會出現報錯
解決方法:
dict.get(key, default=None)
try: child_url = requests.get(news, headers=headers) mypage = child_url.content.decode("gbk") except: # allow_redirects=False 拒絕預設的301/302重定向從而可以通過html.headers["Location"]拿到重定向的URL error_url = requests.get(news, headers=headers, allow_redirects=False) # 200(成功): 伺服器已成功處理了請求。通常,這表示伺服器提供了請求的網頁 # 301(永久移動) : 請求的網頁已永久移動到新位置。伺服器返回此響應(對 GET 或 HEAD 請求的響應)時,會自動將請求者轉到新位置 print(error_url.status_code) try: # 301 mypage = error_url.headers["Location"] except: # 200 mypage = error_url.content.decode("gbk")