使用 chardet 可以很方便的實現字符串/文件的編碼檢測。尤其是中文網頁,有的頁面使用GBK/GB2312,有的使用UTF8,如果你需要去爬一些頁面,知道網頁編碼很重要的,雖然HTML頁面有charset標簽,但是有些時候是不對的。那么chardet就能幫我們大忙了。
chardet的安裝
pip install chardet
chardet實例
>>> import urllib >>> rawdata = urllib.urlopen('http://www.google.cn/').read() >>> import chardet >>> chardet.detect(rawdata) {'confidence': 0.98999999999999999, 'encoding': 'GB2312'} >>>
chardet可以直接用detect函數來檢測所給字符的編碼。函數返回值為字典,有2個元數,一個是檢測的可信度,另外一個就是檢測到的編碼
chardet實例2
import requests import chardet response = requests.get(“http://www.baidu.com”) encode = chardet.detect(response.content) #response.content返回的是bytes型的數據, 如獲取圖片、文件 print(encode)
{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
response.encoding = encode["encoding"] print(response.text) #response.text返回的是Unicode型的數據。 如獲取文本