1、分析
a)《HTTP權威指南》里第16章國際化里提到,如果HTTP響應中Content-Type字段沒有指定charset,則默認頁面是'ISO-8859-1'編碼。一般現在頁面編碼都直接在html頁面中
這處理英文頁面當然沒有問題,但是中文頁面,就會有亂碼了!
b)分析requests的源代碼發現,content是urllib3讀取回來的原始字節碼,而text不過是嘗試對content通過編碼方式解碼為unicode,即text返回的是處理過的Unicode型的數據,而使用content返回的是bytes型的原始數據,程序只通過http響應首部獲取編碼,假如響應中,沒有指定charset, 那么直接返回'ISO-8859-1'。
c)本文中返回的html編碼為utf-8,所以解碼時出現了問題
2、解決辦法
a)requests模塊中自帶該屬性,但默認並沒有用上,所以我們可以直接執行encoding為正確編碼,讓response.text正確解碼即可
import requests url = 'http://192.168.127.129/bugfree/index.php/site/login' data = { 'username': 'admin', 'password': '123456', 'language': 'zh_cn', 'rememberMe': '0' } header = { 'User-Agent': 'Mozilla/5.0' } cookie = { '1_product': 'a6c11f988efefbf5398458aaf673011a504bf08ds%3A1%3A%221%22%3B', 'pageSize': '6f3ba80f2ac7df7b59e81c6cacbe4c041c5a706ds%3A2%3A%2220%22%3B', 'PHPSESSID': 'ku858m8vbmli7hp4inic0pifh7', 'language': 'bece46be16477e1ab82f9d40a53074cb0a54e105s%3A5%3A%22zh_cn%22%3B' } res = requests.post(url,data,headers=header,cookies=cookie) res.encoding = res.apparent_encoding print(res.text)
b)由於content是HTTP相應的原始字節串,所以我們需要直接可以通過使用它。把content按照頁面編碼方式解碼為unicode!
import requests url = 'http://192.168.127.129/bugfree/index.php/site/login' data = { 'username': 'admin', 'password': '123456', 'language': 'zh_cn', 'rememberMe': '0' } header = { 'User-Agent': 'Mozilla/5.0' } cookie = { '1_product': 'a6c11f988efefbf5398458aaf673011a504bf08ds%3A1%3A%221%22%3B', 'pageSize': '6f3ba80f2ac7df7b59e81c6cacbe4c041c5a706ds%3A2%3A%2220%22%3B', 'PHPSESSID': 'ku858m8vbmli7hp4inic0pifh7', 'language': 'bece46be16477e1ab82f9d40a53074cb0a54e105s%3A5%3A%22zh_cn%22%3B' } res = requests.post(url,data,headers=header,cookies=cookie) print(res.content.decode('utf-8'))
解決前:
解決后:
參考博文:https://www.cnblogs.com/bitpeng/p/4748872.html;
https://blog.csdn.net/feixuedongji/article/details/82984583