跳至正文
-
关注
IT极限技术分享汇

ITmax

IT极限技术分享汇

ITmax

  • 首页
  • 商店
  • 我的帐户
  • 结账
  • 购物车
  • 首页
  • 商店
  • 我的帐户
  • 结账
  • 购物车
关

搜索

技术分享

python 的 requests 字符编码乱码,添加 chardet 更加智能、精确的判断 response 的编码

作者 product
2025年2月7日 1 分钟阅读
0

seo 优化:

  • python 的 requests 是怎么判断 response 的字符编码的?
  • python 的 requests 字符编码乱码,添加 chardet 更加智能、精确的判断 response 的编码,避免乱码

下面我展示一下我的代码示例,把 response 的前 256 个字节喂给 chardet 用于判断字符编解码

为什么是 256 个字符?因为太少会判断不准,比如设置成 64 个字节的话,还挺不准的

但是也不要太长了,不然 CPU 要跑很久,非常性能和时间

具体的,各位可以自己平衡准确率和性能耗时

import requests
import chardet
from loguru import logger


def check_encoding(stream: bytes) -> str | None:
    encoding = chardet.detect(stream[:256]).get('encoding', None)
    return encoding


def download(url: str) -> str:
    response = requests.get(url, timeout=30)

    response.encoding = check_encoding(response.content) or 'utf-8'
    logger.debug(f'长度为 {len(response.text)} 字符, 编码为: {response.encoding}')
    return response.text

不过有一个缺点就是 chardet 不维护了

https://pypi.org/project/chardet/#history

图片.png

https://github.com/chardet/chardet

https://segmentfault.com/a/1190000046086292

作者

product

关注我
其他文章
上一个

IDEA 接入 DeepSeek,太酷了!

下一个

reqable 在 Firefox 浏览器无法抓包和访问网络

暂无评论!成为第一个。

发表回复 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Copyright 2026 — IT极限技术分享汇. 备案号:浙ICP备17006560号-2