Python BeautifulSoup写入HTML标签时转义问题求助
解决BeautifulSoup插入HTML标签被转义为实体的问题
问题场景
使用以下代码操作本地HTML文件时:
from bs4 import BeautifulSoup soup = BeautifulSoup(open('input.html', encoding="utf-8"), 'lxml') #local html file soup.select_one("#target").clear() soup.select_one("#target").insert(0, "<h1>Heading</h1>") with open("output.html", "w", encoding="utf-8") as file: file.write(str(soup))
执行后插入的内容被转为字符串实体,结果如下:
<div id="target"><h1>Heading</h1></div>
期望得到实际的HTML标签:
<div id="target"><h1>Heading</h1></div>
解决方案
方法1:解析HTML片段后插入
将HTML字符串用BeautifulSoup解析为标签对象,再插入目标容器:
from bs4 import BeautifulSoup soup = BeautifulSoup(open('input.html', encoding="utf-8"), 'lxml') target = soup.select_one("#target") target.clear() # 解析HTML片段生成可插入的标签结构 new_content = BeautifulSoup("<h1>Heading</h1>", 'lxml') target.append(new_content) with open("output.html", "w", encoding="utf-8") as file: file.write(str(soup))
方法2:手动创建标签并添加
通过new_tag方法创建指定标签,设置内容后插入:
from bs4 import BeautifulSoup soup = BeautifulSoup(open('input.html', encoding="utf-8"), 'lxml') target = soup.select_one("#target") target.clear() # 创建h1标签 h1_tag = soup.new_tag("h1") # 设置标签文本内容 h1_tag.string = "Heading" # 插入到目标容器的开头 target.insert(0, h1_tag) with open("output.html", "w", encoding="utf-8") as file: file.write(str(soup))
原因说明
直接向insert方法传入字符串时,BeautifulSoup会将其视为纯文本,自动转义<、>等HTML特殊字符。只有传入BeautifulSoup解析后的Tag对象或手动创建的标签实例,才会被识别为HTML元素插入到文档中。
内容的提问来源于stack exchange,提问作者aboutjquery
相关产品推荐
相关产品推荐

