Python requests庫中文亂碼問題

當使用requests庫的時候,會出現中文亂碼的狀況html

參考代碼分析Python requests庫中文編碼問題python

      Python HTTP庫requests中文頁面亂碼解決方案!app

分析post

根據這兩篇文章可知:測試

    分析requests的源代碼發現,text返回的是處理過的Unicode型的數據,而使用content返回的是bytes型的原始數據。也就是說,r.content相對於r.text來講節省了計算資源,content是把內容bytes返回. 而text是decode成Unicode. 若是headers沒有charset字符集的化,text()會調用chardet來計算字符集,這又是消耗cpu的事情.ui

import requests

response = requests.get('http://www.dytt8.net/index.htm')
print(response.text[200:300])

這裏測試使用電影天堂的網頁,由於網頁不太標準編碼

輸出爲url

  

輸出了亂碼spa

response.encoding.net

從第二篇文章能夠知道reqponse header只指定了type,可是沒有指定編碼(通常如今頁面編碼都直接在html頁面中),查找原網頁能夠看到

再找一個標準點的網頁查看,好比博客園的網頁博客園

response herders的Content-Type指定了編碼類型

《HTTP權威指南》裏第16章國際化裏提到,若是HTTP響應中Content-Type字段沒有指定charset,則默認頁面是'ISO-8859-1'編碼。這處理英文頁面固然沒有問題,可是中文頁面,就會有亂碼了!

解決

若是在肯定使用text,並已經得知該站的字符集編碼時,能夠使用 r.encoding = ‘xxx’ 模式, 當你指定編碼後,requests在text時會根據你設定的字符集編碼進行轉換. 

使用apparent_encoding能夠得到真實編碼

>>> response.apparent_encoding
'GB2312'

這是程序本身分析的,會比較慢

還能夠從html的meta中抽取

>>> requests.utils.get_encodings_from_content(response.text)
['gb2312']

解決方法

# response.encoding = response.apparent_encoding
response.encoding = 'gb2312'

這時候的輸出爲

  

  

  

 

 

Python HTTP庫requests中文頁面亂碼解決方案!

相關文章
相關標籤/搜索