Python100个库分享第1个—Chardet

目录

专栏导读

🌸 欢迎来到Python办公自动化专栏---Python处理办公问题,解放您的双手

🏳️‍🌈 博客主页:请点击------> 一晌小贪欢的博客主页求关注

👍 该系列文章专栏:请点击------>Python办公自动化专栏求订阅

🕷 此外还有爬虫专栏:请点击------>Python爬虫基础专栏求订阅

📕 此外还有python基础专栏:请点击------>Python基础学习专栏求订阅

文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏

❤️ 欢迎各位佬关注! ❤️

库的介绍

chardet的使用非常简单,主模块里面只有一个函数detect。detect有一个参数,要求是bytes类型。bytes类型可以通过读取网页内容、open函数的rb模式、带b前缀的字符串、encode函数等途径获得。

安装

python 复制代码
pip install chardet

测试代码

python 复制代码
import chardet

str1 = 'hello wyt'.encode('utf-8')  # encode 接受str,返回一个bytes
print(type(str1),str1)

result = chardet.detect(str1)  # chardet 接受bytes类型,返回一个字典,返回内容为页面编码类型.
print(type(result),result)
codetype = result.get('encoding')
print(codetype)

输出

python 复制代码
<class 'bytes'> b'hello wyt'
<class 'dict'> {'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
ascii

常见用法

一般用chardet查看构造请求的返回内容网页中的编码形式,以下定义意义为:以ascii码发送http响应信息

python 复制代码
mport chardet
import requests

# 定义要请求的URL
url = 'https://www.baidu.com'

try:
    # 发起GET请求
    res = requests.get(url)
    # 检测响应内容的编码
    codetype = chardet.detect(res.content)['encoding']
    # 设置响应的编码
    res.encoding = codetype
    # 打印响应对象
    print(res)
    # 如果需要打印响应文本,可以这样做
    # print(res.text)
except requests.exceptions.RequestException as e:
    # 处理请求异常
    print(f"发生了一个请求异常: {e}")

总结

希望对初学者有帮助

致力于办公自动化的小小程序员一枚

希望能得到大家的【一个免费关注】!感谢

求个 🤞 关注 🤞

此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏

求个 ❤️ 喜欢 ❤️

此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏

求个 👍 收藏 👍

此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏

相关推荐
老胖闲聊3 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1183 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之3 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
lyaihao4 小时前
使用python实现奔跑的线条效果
python·绘图
ai大师5 小时前
(附代码及图示)Multi-Query 多查询策略详解
python·langchain·中转api·apikey·中转apikey·免费apikey·claude4
小小爬虾5 小时前
关于datetime获取时间的问题
python
蓝婷儿6 小时前
6个月Python学习计划 Day 16 - 面向对象编程(OOP)基础
开发语言·python·学习
chao_7897 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
大霞上仙7 小时前
nonlocal 与global关键字
开发语言·python
Mark_Aussie8 小时前
Flask-SQLAlchemy使用小结
python·flask