python - 写入 html 文件转换特殊字符
python - writing into html file converts the special characters
我正在尝试使用 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 文件,我添加的任何标签都被隐藏了
例如<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>