Python100个库分享第1个—Chardet

专栏导读

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

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

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

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

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

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

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

库的介绍

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

安装

pip install chardet

测试代码

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)
  • 输出

<class 'bytes'> b'hello wyt'
<class 'dict'> {'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
ascii

常见用法

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

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基础学习专栏

相关推荐

  1. Python100分享1Chardet

    2024-03-29 22:40:03       39 阅读
  2. Python100分享4—difflib

    2024-03-29 22:40:03       41 阅读
  3. 100python代码(三)

    2024-03-29 22:40:03       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-29 22:40:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-29 22:40:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-29 22:40:03       82 阅读
  4. Python语言-面向对象

    2024-03-29 22:40:03       91 阅读

热门阅读

  1. Ubuntu 的cuda更新

    2024-03-29 22:40:03       38 阅读
  2. 【python学习】基础篇-命名规范

    2024-03-29 22:40:03       41 阅读
  3. 项目中线程池的应用

    2024-03-29 22:40:03       54 阅读
  4. Pandas合并数据集

    2024-03-29 22:40:03       35 阅读
  5. 每日一题(leetcode2909):单份查找与群组查找

    2024-03-29 22:40:03       44 阅读