解決爬取網站過程中遇到的HTTP Error 302錯誤和中文亂碼問題


今天嘗試爬取國家稅務總局網站
from urllib import request
base_url = "http://www.chinatax.gov.cn/chinatax/n810219/n810724/index.html"
f = request.urlopen(base_url)

用上面這段代碼,結果會報錯:

urllib.error.HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop.

找了一下原因,也沒太看懂,大概是 因為沒有cookies,而網站需要cookies, 問題在這里:
后來在別的地方有人說,可以用requests這個庫來抓取信息就不會,於是用了這個庫
import requests
res = requests.get("http://www.chinatax.gov.cn/chinatax/n810219/n810724/index.html")
print(res.text)

 

寫了上面的代碼,可以抓取了,但是又遇到一個新問題,就是抓取網頁里的中文是亂碼
然后又在網上尋找辦法,試了很多方法,但最終解決問題很簡單
 
import requests
res = requests.get("http://www.chinatax.gov.cn/chinatax/n810219/n810724/index.html")
res.encoding= 'utf-8'     # 指定res的編碼
print(res.text)

最終,問題解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM