requests默认编码不准,因优先读取HTTP头charset,缺失时用chardet猜,而chardet对无BOM的GBK/GB2312页面误判率高;且response.encoding设错后无法修正已生成的.text,故应弃用.text,改用content配合charset_normalizer或meta标签提取真实编码再decode。

为什么 requests.get() 默认编码经常不准?
requests 库在调用 response.text 时,会优先读取 HTTP 头里的 Content-Type(如 text/html; charset=utf-8),没声明或声明模糊(比如只有 text/html)时,就 fallback 到 chardet.detect() 猜测,而 chardet 对短文本、无 BOM 的 GBK/GB2312 页面误判率很高——尤其中文新闻站、政府老系统页面,常把 GBK 识别成 CP1252 或 ISO-8859-1,一解码就变乱码。
更麻烦的是:response.encoding 一旦被设过(哪怕设错),后续再改也不会影响已生成的 response.text,这是很多人反复调试不生效的根本原因。
手动指定 encoding 前必须先关掉自动推断
别在拿到 response 后直接改 response.encoding 再取 .text——这招只对未访问过 .text 的 response 有效。正确做法是:跳过 .text,直接用 response.content(原始 bytes)交给 chardet 或 charset_normalizer 判断,再显式 decode。
-
charset_normalizer比chardet更准、更快,且对中文编码(GBK/GB2312/GB18030)支持更好,推荐替换 - 安装:
pip install charset-normalizer - 关键逻辑:先用
charset_normalizer.from_bytes(response.content)得到可信度最高的编码,再response.content.decode(编码)
示例:
Camoufox 是一个基于 Firefox 构建的开源反检测浏览器,为 Python 自动化工作流程提供强大的指纹注入和反机器人检测规避功能。它与 Playwright 集成,以提供能够绕过现代机器人检测系统的隐身浏览能力。
import requests
from charset_normalizer import from_bytes
<p>resp = requests.get("<a href="https://www.php.cn/link/94b5015ed9312454d91af3a6b1f4b1dd">https://www.php.cn/link/94b5015ed9312454d91af3a6b1f4b1dd</a>")
if resp.content:</p><h1>必须用 content,不能用 text</h1><pre class="brush:php;toolbar:false;">detected = from_bytes(resp.content)
if detected:
encoding = detected[0].confidence > 0.7 and detected[0].encoding
text = resp.content.decode(encoding or "utf-8", errors="replace")
HTML meta charset 标签比 HTTP header 更可靠
很多网站 HTTP header 不带 charset,但 HTML 里有 閹
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










