Python3的requests類抓取中文頁面出現亂碼的解決辦法
阿新 • • 發佈:2018-03-03
view www. .com ons 分享圖片 exceptio code gem tex
這種亂碼現象基本上都是編碼造成的,我們要轉到我們想要的編碼,先po一個知識點,嵩天老師在Python網絡爬蟲與信息提取說到過的:response.encoding是指從HTTP的header中猜測的響應內容編碼方式,如果header中不存在charset,則默認編碼為ISO-8859-1 ,這樣一來某些不規範的服務器返回就必然亂碼了;response.apparent_encoding是指從內容中分析出的響應內容編碼方式。requests內部的 utils 也提供了一個從返回 body 獲取頁面編碼的函數get_encodings_from_content,這樣如果服務器返回的頭不含 Charset,再通過 get_encodings_from_content 就可以知道頁面的正確編碼了。下面是調試的過程:
import requests
from requests.exceptions import RequestException
def get_one_page(url):
try:
response=requests.get(url)
if response.status_code == 200:
#print(response.text)
print(response.encoding)
print(response.apparent_encoding)
r =response.text
print(requests.utils.get_encodings_from_content(r)[0])
a=r.encode(‘ISO-8859-1‘).decode(requests.utils.get_encodings_from_content(r)[0])
print(a)
print(‘------------------------------------‘)
b = r.encode(‘ISO-8859-1‘).decode(response.apparent_encoding)
print(b)
return None
except RequestException:
return None
def main():
url = ‘http://www.mh160.com/‘
get_one_page(url)
if __name__==‘__main__‘:
main()
看圖!看圖!看圖!
Python3的requests類抓取中文頁面出現亂碼的解決辦法