专栏导读
-
🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
-
🏳️🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注
-
👍 该系列文章专栏:请点击——>Python办公自动化专栏求订阅
-
🕷 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅
-
📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
-
文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏
-
❤️ 欢迎各位佬关注! ❤️
库的介绍
-
chardet的使用非常简单,主模块里面只有一个函数detect。detect有一个参数,要求是bytes类型。bytes类型可以通过读取网页内容、open函数的rb模式、带b前缀的字符串、encode函数等途径获得。
安装
pip install chardet
测试代码
import chardetstr1 = '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 = codetypeprint(res)
except requests.exceptions.RequestException as e:print(f"发生了一个请求异常: {e}")
总结
-
希望对初学者有帮助
-
致力于办公自动化的小小程序员一枚
-
希望能得到大家的【一个免费关注】!感谢
-
求个 🤞 关注 🤞
-
此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏
-
求个 ❤️ 喜欢 ❤️
-
此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏
-
求个 👍 收藏 👍
-
此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏