
使用 BeautifulSoup 的 append() 直接插入 HTML 字符串会导致标签被自动转义(如 变成 ),正确做法是通过 soup.new_tag() 创建真实标签对象再插入,既保留结构又兼容 UTF-8(含韩文等多语言)内容。
使用 beautifulsoup 的 append() 直接插入 html 字符串会导致标签被自动转义(如 <p></p> 变成 <p></p>),正确做法是通过 soup.new_tag() 创建真实标签对象再插入,既保留结构又兼容 utf-8(含韩文等多语言)内容。
在 BeautifulSoup 中,append() 方法对字符串参数会将其视为纯文本(text node)而非 HTML 结构,因此所有 , <code>>, & 等字符都会被自动 HTML 转义,以防止 XSS 或解析错误。这正是你看到 <p></p> 变成 <p></p> 的根本原因——不是编码问题,而是语义误判。
✅ 正确做法:使用 soup.new_tag() 构造标签节点
from bs4 import BeautifulSoup
# 安全读取含韩文的 HTML 文件(推荐显式指定 encoding)
with open("test/test.html", "r", encoding="utf-8") as f:
soup = BeautifulSoup(f, "html.parser")
# ✅ 正确:创建真实 <p> 标签并设置文本内容
p = soup.new_tag("p")
p.string = "exampletext" # 支持 UTF-8 字符,如 "안녕하세요"
soup.body.append(p)
# ✅ 若需嵌套 HTML(如含子标签),用 append() 添加子节点或使用 .extend()
strong = soup.new_tag("strong")
strong.string = "重点"
p.append(strong) # → </p><p>exampletext<strong>重点</strong></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill9972" title="Wechat Article Html"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e695c2374.jpg" alt="Wechat Article Html" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill9972" title="Wechat Article Html" class="overflowclass">Wechat Article Html</a>
<p class="overflowclass">将 Markdown 文章转换为微信公众号兼容的纯 HTML 格式。当用户要求"转成微信格式"、"生成公众号文章 HTML"、"排版到微信草稿箱"、"微信粘贴格式"时触发。输出带内联样式的纯 HTML,微信编辑器可直接渲染,无需额外适配。支持标题、段落、列表、粗体、行内代码、表格、引用块、代码块、配图的完整转换。</p>
</div>
<a rel="nofollow" href="/xiazai/skill9972" title="Wechat Article Html" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
# 写入文件(保持 UTF-8 编码,无需额外 from_encoding)
with open("test/result.html", "w", encoding="utf-8") as f:
f.write(str(soup))
⚠️ 注意事项:
- ❌ 避免
soup.body.append("<p>...</p>")—— 字符串会被转义; - ✅ 优先用
soup.new_tag()+.string/.append()组合构建结构; - ✅ 若需批量插入 HTML 片段,可用
BeautifulSoup(html_str, "html.parser").body.contents提取节点后逐个append(); - ? UTF-8 支持关键在于 文件读写时显式指定
encoding="utf-8",与from_encoding参数无关(该参数已弃用于现代 BS4); - ? 验证韩文是否正常:打印
soup.body.get_text()应完整显示原始韩文,无乱码。
总结:BeautifulSoup 的核心原则是“操作对象,而非字符串”。将 HTML 片段作为字符串拼接是反模式;始终通过 API 创建和组装 Tag 对象,才能兼顾安全性、可维护性与多语言支持。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










