专栏导读
🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏
❤️ 欢迎各位佬关注! ❤️
库的介绍
chardet的使用非常简单,主模块里面只有一个函数detect。detect有一个参数,要求是bytes类型。bytes类型可以通过读取网页内容、open函数的rb模式、带b前缀的字符串、encode函数等途径获得。
安装
pip install chardet
测试代码
import chardet
str1 = 'hello wyt'.encode('utf-8')
print(type(str1),str1)
result = chardet.detect(str1)
print(type(result),result)
codetype = result.get('encoding')
print(codetype)
<class 'bytes'> b'hello wyt'
<class 'dict'> {'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
ascii
常见用法
一般用chardet查看构造请求的返回内容网页中的编码形式,以下定义意义为:以ascii码发送http响应信息
mport chardet
import requests
url = 'https://www.baidu.com'
try:
res = requests.get(url)
codetype = chardet.detect(res.content)['encoding']
res.encoding = codetype
print(res)
except requests.exceptions.RequestException as e:
print(f"发生了一个请求异常: {e}")
总结
希望对初学者有帮助
致力于办公自动化的小小程序员一枚
希望能得到大家的【一个免费关注】!感谢
求个 🤞 关注 🤞
求个 ❤️ 喜欢 ❤️
求个 👍 收藏 👍