You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup4爬取网页出现乱码问题求助

解决BeautifulSoup4爬取时内容乱码且终端崩溃的问题

嘿,我懂你现在的糟心状况——明明网站标了utf-8编码,换了好几个HTML解析器,还试了解码操作,结果里全是看不懂的乱码,甚至把终端都搞崩了。咱们一步步拆解问题,把它搞定!

核心问题分析

大概率是这两个原因:

  1. 网站标了utf-8,但实际返回的内容是gzip压缩过的原始字节,或者用了其他编码(比如gbk、iso-8859-1),硬解码utf-8自然会乱码;
  2. 乱码里混了大量终端无法识别的控制字符,直接print就会导致终端崩溃。

具体解决方案,按顺序试:

1. 优先用requests处理编码与压缩(最省心)

requests库能自动识别响应编码,还能处理常见的压缩格式,比原生urllib好用太多:

import requests
from bs4 import BeautifulSoup
import gzip
from io import BytesIO

# 替换成你的目标网站URL
target_url = "https://你的目标网站地址.com"
response = requests.get(target_url)

# 检查内容是否被gzip压缩(很多网站都会这么做)
if response.headers.get('Content-Encoding') == 'gzip':
    # 解压压缩内容
    compressed_buffer = BytesIO(response.content)
    decompressed_content = gzip.GzipFile(fileobj=compressed_buffer)
    html_content = decompressed_content.read().decode('utf-8', 'ignore')
else:
    # 用requests自动识别的编码解码,别硬写utf-8
    html_content = response.content.decode(response.encoding, 'ignore')

# 解析并写入文件(避免终端崩溃)
bs_obj = BeautifulSoup(html_content, "html5lib")
with open("爬取结果.html", "w", encoding="utf-8") as f:
    f.write(bs_obj.prettify())

2. 坚持用urllib的话,这么改

如果不想换库,一定要先获取响应的实际编码,而不是强制用utf-8:

from urllib.request import urlopen
from bs4 import BeautifulSoup

response = urlopen("https://你的目标网站地址.com")
# 从响应头获取真实编码,失败才用utf-8兜底
actual_encoding = response.info().get_content_charset(failobj="utf-8")
html_content = response.read().decode(actual_encoding, 'ignore')

# 解析后写入文件,避免终端崩溃
bs_obj = BeautifulSoup(html_content, "html5lib")
with open("爬取结果.html", "w", encoding="utf-8") as f:
    f.write(bs_obj.prettify())

3. 解决终端崩溃问题

乱码里的不可打印控制字符是终端崩溃的元凶,要么写入文件查看,要么先过滤再打印:

import string

# 过滤所有不可打印字符
cleaned_html = ''.join(filter(lambda char: char in string.printable, html_content))
bs_obj = BeautifulSoup(cleaned_html, "html5lib")
print(bs_obj.prettify())

额外提醒

如果试完上面的方法还是乱码,那可能网站有反爬机制(返回加密内容),或者内容是JavaScript动态加载的。这种情况就得换思路,比如用Selenium模拟浏览器加载,但先把编码和压缩的问题解决再说——大概率是这个原因导致的。

内容的提问来源于stack exchange,提问作者OrigamiEye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:34:44