今天嘗試爬取國家稅務總局網站
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)
最終,問題解決。