我正在尝试使用 python 写入 html 文件,我添加的任何标签都会被隐藏
例如<tr>
至<tr>
知道为什么会发生这种情况以及如何避免它吗?
在 html 页面中,会显示我插入的确切文本,而不是被视为 html 标签
部分代码:
htmlReport=ElementTree()
htmlReport.parse('result_templte.html')
strTable="<tr><td>Text here</td></tr>"
for node in htmlReport.findall('.//*[@id="table1"]')
node.text=strTable
htmlReport.write("results.html")
这会将 html 标签写入 <
>
到文件中。因此插入的标签不会被视为正确的 html 标签
最佳答案
您正在尝试添加一个元素作为另一个元素的子元素,但实际上您只是添加一个恰好包含 <
的纯文本字符串。和>
标记分隔符。为了使其工作,您需要解析字符串以获取新的元素对象并将其添加(追加)到正确的位置。
假设 template.html 如下所示:
<html>
<table>
</table>
<table id="table1">
</table>
</html>
然后你可以添加tr
元素作为第二个 table
的子元素如下:
from xml.etree import ElementTree as ET
tree = ET.parse('template.html')
# Get the wanted 'table' element
table = tree.find(".//table[@id='table1']")
# Parse string to create a new element
tr = ET.fromstring("<tr><td>Text here</td></tr>")
# Append 'tr' as a child of 'table'
table.append(tr)
tree.write("results.html")
这是 results.html 的样子:
<html>
<table>
</table>
<table id="table1">
<tr><td>Text here</td></tr></table>
</html>
关于python - 写入html文件转换特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31941943/