Requests爬取網頁的編碼問題
import requests
from requests import exceptions
def getHtml():
try:
r=requests.get('http://www.zuihaodaxue.com/zuihaodaxuepaiming2017.html')
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except requests.RequestException as e:
return ''
其中 r.encoding 根據響應頭中的 charset 判斷網站編碼,如果沒有設置則默認返回 iso-8859-1 編碼,而r.apparent_encoding
則通過網頁內容來判斷其編碼。令r.encoding=r.apparent_encoding就不會出現亂碼問題。