【问题标题】:python - writing into html file converts the special characterspython - 写入html文件转换特殊字符
【发布时间】:2015-08-11 12:33:51
【问题描述】:

我正在尝试使用 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 标记作为 &amp;lt; &amp;gt; 写入文件中。所以插入的标签不会被视为正确的html标签

【问题讨论】:

  • 没有任何其他库的纯 Python 代码,将字符串 '&lt;tr&gt;' 写入文件不会转义 HTML,因此您不只是使用纯 Python。请告诉我们minimal reproducible example,这样我们就可以对为什么您的文本被转义说一些有意义的事情。
  • 更新了文字,希望对您有所帮助
  • 您是否有不想使用真正的模板引擎的原因,例如Jinja2

标签: python html elementtree


【解决方案1】:

您试图将一个元素添加为另一个元素的子元素,但实际上您只是添加了一个纯文本字符串,该字符串恰好包含&lt;&gt; 标记分隔符。为了使其工作,您需要解析字符串以获取新的元素对象并将其添加(附加)到正确的位置。

假设 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 2016-05-31
    • 2021-05-26
    • 2012-03-25
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多