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


universe_king
3.4k 声望680 粉丝