34  
查询码: 00000640
Python chardet字符编码的判断 - 小鳄鱼DL - 博客园
来源:https://www.cnblogs.com/longsongpong/p/10077948.html
作者: 周杨 于 2022年09月09日 发布在分类 / 计算机应用 / 编程 ,于 2022年09月09日 编辑
chardet 编码 response import 返回 encoding 页面 鳄鱼 字符 检测



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




 历史版本

备注 修改日期 修改人
CREAT 2022-09-09 22:44:26[当前版本] 系统管理员

  目录
    知识分享平台 -V 5.1.4 -大信谛威