python 获取网页乱码怎么解决

17次阅读

python网页乱码主因是响应编码与解码方式不一致,需手动指定response.encoding或用chardet检测后设置,也可直接对r.content调用decode()并处理异常,还可解析html meta标签获取charset声明。

python 获取网页乱码怎么解决

Python 获取网页出现乱码,核心原因是网页编码(如 UTF-8、GBK、GB2312)与你读取时使用的解码方式不一致。解决的关键是**正确识别并指定响应内容的编码格式**,而不是盲目用默认编码或乱试。

检查并手动指定 response.encoding

requests 库的 response.text 会根据 response.encoding 自动解码。但 requests 有时会误判编码(比如把 GBK 网页识别成 ISO-8859-1),导致乱码。此时应手动覆盖:

  • 先用 response.content(原始字节)查看前几百字节,用文本编辑器或 chardet 探测真实编码
  • 确认后,显式设置 response.encoding = 'GBK''UTF-8',再取 response.text
  • 示例:
      import requests
      r = requests.get(‘http://example.com’)
      r.encoding = ‘GBK’  # 强制指定
      print(r.text)

用 chardet 自动检测编码(适合不确定来源的网页)

对于编码未知的老站或中文站点,chardet 是实用工具。注意它基于字节统计,对短文本可能不准,建议只检测前 100KB:

  • 安装:pip install chardet
  • 使用:
      import chardet
      raw = r.content[:100000]  # 截取前10万字节提高准确率
      detected = chardet.detect(raw)
      print(detected[‘encoding’], detected[‘confidence’])
      r.encoding = detected[‘encoding’] or ‘utf-8’
      print(r.text)

直接用 content + decode() 更可控

绕过 requests 的自动解码逻辑,自己处理字节流,避免 encoding 属性被污染:

立即学习Python免费学习笔记(深入)”;

  • r.content 是原始 bytes,可安全传给 .decode()
  • 配合 try/except 处理解码失败(如部分字节非法):
      try:
        text = r.content.decode(‘utf-8’)
      except UnicodeDecodeError:
        text = r.content.decode(‘gbk’, errors=’ignore’)
  • errors='ignore' 跳过非法字符,'replace' 替换为 ,按需选择

留意网页 meta 中的 charset 声明

有些网页在 HTML 的

text=ZqhQzanResources