1. 解決中文亂碼的一種可行方法
1 # -*- coding:utf-8 -*- 2 from __future__ import unicode_literals 3 4 import chardet 5 6 7 def smart_decoder(raw_content, default_encoding_list=("utf-8", "gb18030")): 8 """ 9 將字符串解碼成unicode 10 :type default_encoding_list: list of str 11 :rtype: unicode 12 :type raw_content: str|unicode 13 """ 14 if isinstance(raw_content, unicode): 15 return raw_content 16 17 encoding = chardet.detect(raw_content).get("encoding", "utf-8") 18 19 try: 20 return raw_content.decode(encoding) 21 except UnicodeEncodeError as e: 22 for encoding in default_encoding_list: 23 try: 24 return raw_content.decode(encoding) 25 except UnicodeEncodeError as e: 26 pass 27 raise e 28 29 30 if __name__ == '__main__': 31 import requests 32 33 a = requests.get("https://www.baidu.com").content 34 smart_decoder(a)
2. requests響應結果亂碼
使用requests請求網址,獲取響應response, 通過response.text得到的網頁內容,有時候會出現亂碼的情況。
原因:
分析源代碼發現,調用respose.text 其實就是對 response.content執行解碼操作。編碼通過chardet判斷。
亂碼的關鍵是,chardet獲取的編碼可能不正確,但在執行response.content.decode時,程序會直接忽略編碼異常,從而導致使用錯誤的編碼解碼。
解決思路:
人工解碼,處理編碼錯誤
程序demo
1 def parse_response(response): 2 """ 3 手工對requests的響應內容解碼 4 :rtype: unicode 5 """ 6 return smart_decoder(response.content)
源碼見blog.