简体   繁体   English

python-写入html文件可转换特殊字符

[英]python - writing into html file converts the special characters

I am trying to write into a html file using python, any tags that I add are getting coverted 我正在尝试使用python写入html文件,我添加的所有标签都被隐藏了

eg <tr> to &lt;tr&gt; 例如<tr>&lt;tr&gt;

Any idea why this is happening and how to avoid it? 知道为什么会这样以及如何避免吗?

In the html page, the exact text that I inserted appears rather than being treated as html tags 在html页面中,我插入的确切文本出现,而不是被视为html标签

Part of the Code: 部分代码:

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")

this writes the html tag as &lt; 这会将html标记写为&lt; &gt; into the file. 到文件中。 so the tags inserted are not treated as proper html tags 因此插入的标签不会被视为正确的html标签

You are trying to add an element as a child of another element, but you are actually just adding a plain text string that happens to contain < and > markup delimiters. 您试图将一个元素添加为另一个元素的子元素,但实际上您只是添加了一个纯文本字符串,该字符串恰好包含<>标记定界符。 To make it work, you need to parse the string to get a new element object and add (append) it in the right place. 要使其工作,您需要解析该字符串以获取一个新的元素对象,并将其添加(附加)到正确的位置。

Let's assume that template.html looks like this: 假设template.html看起来像这样:

<html>

 <table>
 </table>

 <table id="table1">
 </table>

</html>

Then you can add a tr element as a child of the second table as follows: 然后,可以将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")

This is what results.html looks like: 这是result.html的样子:

<html>

 <table>
 </table>

 <table id="table1">
 <tr><td>Text here</td></tr></table>

</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM