Python chardet字符编码的判断

  使用 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型的数据。 如获取文本   

 

posted @ 2018-12-06 17:23  小鳄鱼DL  阅读(2241)  评论(0编辑  收藏  举报