乱码主因是response.content被错误解码为str后再传给beautifulsoup,导致字节信息损坏;正确做法是直接传bytes并显式指定from_encoding参数,如soup = beautifulsoup(r.content, 'html.parser', from_encoding='gb18030')。

乱码网页不是编码问题本身,而是 BeautifulSoup 没有正确识别或强制指定编码时,response.content 被错误解码成 str 后再喂给解析器——此时原始字节信息已损坏,再怎么调 BeautifulSoup 的 from_encoding 参数都无效。
先确认乱码是编码问题,不是网页本身内容异常
直接检查原始响应字节流,别急着用 response.text:
-
response.content[:100]看前 100 字节是否含可读中文(如b'\xe4\xbd\xa0\xe5\xa5\xbd'是 UTF-8 的“你好”) - 对比
response.headers.get('content-type')中的charset(如charset=gb2312),但别盲目信任——很多老站 header 是错的或缺失 - 用
chardet.detect(response.content)猜测真实编码(注意:对小文本不准,建议至少 1KB 以上)
用 raw bytes + 显式 encoding 初始化 BeautifulSoup
跳过 requests 自动解码环节,把字节流和你确认/猜测的编码一起传给 BeautifulSoup:
from bs4 import BeautifulSoup import requests <p>r = requests.get(url)</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8054" title="python-parallelization"><img src="https://img.php.cn/upload/skill/000/000/081/179181013081932.jpg" alt="python-parallelization" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill8054" title="python-parallelization" class="overflowclass">python-parallelization</a> <p class="overflowclass">将顺序 Python 代码转换为并行/并发实现,用于在需要并行化 Python 代码、提升性能时使用。</p> </div> <a rel="nofollow" href="/xiazai/skill8054" title="python-parallelization" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div><h1>❌ 错误:r.text 已被 requests 按错误编码转成 str</h1><h1>soup = BeautifulSoup(r.text, 'html.parser')</h1><h1>✅ 正确:用 content + 显式指定 encoding</h1><p>soup = BeautifulSoup(r.content, 'html.parser', from_encoding='gb18030')</p><h1>或 'gb2312'、'utf-8'、'big5',取决于实际检测结果</h1><p></p>
关键点:from_encoding 参数只在传入 bytes 时生效;传 str 会直接忽略它。
遇到混合编码或 meta charset 不一致时强制重编码
有些网页在 <meta charset="gb2312">
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










