問題:urllib.error.HTTPError: HTTP Error 418:
程序:
import urllib.request response=urllib.request.urlopen('https://movie.douban.com/') html=response.read().decode('utf8') print(html)
運行程序讀取網頁時顯示:
“HTTP Error 418:”應該是網站的反爬程序返回的。
在使用瀏覽器訪問網站時,訪問請求中包含請求頭。檢測請求頭是常見的反爬蟲策略。
服務器通過檢測請求頭判斷這次請求是不是人為的。
在程序上加入請求頭,這樣服務器就會認為這是一個從瀏覽器發出的人為請求:
import urllib.request url='https://movie.douban.com/' #請求頭 herders={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1;WOW64) AppleWebKit/537.36 (KHTML,like GeCKO) Chrome/45.0.2454.85 Safari/537.36 115Broswer/6.0.3', 'Referer':'https://movie.douban.com/', 'Connection':'keep-alive'} req=urllib.request.Request(url,headers=herders) response=urllib.request.urlopen(req) html=response.read().decode('utf8') print(html)
返回正確結果。