在 Python 中将 html 标签添加到 XML.ElementTree 元素的文本中

Eri*_*uer 2 html python xml elementtree

我正在尝试使用 python 脚本生成一个 HTML 文档,其中包含使用该XML.etree.ElementTree模块的数据表中的文本。我想格式化一些单元格以包含 html 标签,通常是<br /><sup></sup>标签。当我生成一个字符串并将其写入文件时,我相信 XML 解析器正在将这些标签转换为单个字符。输出将标签显示为文本,而不是将它们作为标签处理。这是一个简单的例子:

import xml.etree.ElementTree as ET

root = ET.Element('html')
   #extraneous code removed
td = ET.SubElement(tr, 'td')
td.text = 'This is the first line <br /> and the second'

tree = ET.tostring(root)
out = open('test.html', 'w+')           
out.write(tree)                     
out.close()
Run Code Online (Sandbox Code Playgroud)

当您打开生成的“test.html”文件时,它显示的文本字符串与键入的完全相同:“这是第一行 <br /> 和第二行”。

HTML 文档本身显示了源代码中的问题。解析器似乎将标记中的“小于”和“大于”符号替换为这些符号的 HTML 表示:

    <!--Extraneous code removed-->
<td>This is the first line %lt;br /&gt; and the second</td>
Run Code Online (Sandbox Code Playgroud)

显然,我的意图是让文档处理标签本身,而不是将其显示为文本。我不确定是否可以通过不同的解析器选项来使其工作,或者是否应该使用不同的方法。如果可以解决问题,我愿意使用其他模块(例如 lxml)。为方便起见,我主要使用内置的 XML 模块。

我发现唯一可行的方法是re在写入文件之前使用替换修改最终字符串:

tree = ET.tostring(root)
tree = re.sub(r'&lt;','<',tree)
tree = re.sub(r'&gt;','>',tree)
Run Code Online (Sandbox Code Playgroud)

这有效,但似乎应该可以通过在xml. 有什么建议?

Anz*_*zel 5

您可以使用和tail属性来构建您想要的文本:tdbr

import xml.etree.ElementTree as ET


root = ET.Element('html')
table = ET.SubElement(root, 'table')
tr = ET.SubElement(table, 'tr')
td = ET.SubElement(tr, 'td')
td.text = "This is the first line "
# note how to end td tail
td.tail = None
br = ET.SubElement(td, 'br')
# now continue your text with br.tail
br.tail = " and the second"

tree = ET.tostring(root)
# see the string
tree
'<html><table><tr><td>This is the first line <br /> and the second</td></tr></table></html>'

with open('test.html', 'w+') as f:
    f.write(tree)

# and the output html file
cat test.html
<html><table><tr><td>This is the first line <br /> and the second</td></tr></table></html>
Run Code Online (Sandbox Code Playgroud)

作为旁注,要包含<sup></sup>和 附加文本但仍在 中<td>,使用tail也会产生期望的效果:

...
td.text = "this is first line "
sup = ET.SubElement(td, 'sup')
sup.text = "this is second"
# use tail to continue your text
sup.tail = "well and the last"

print ET.tostring(root)
<html><table><tr><td>this is first line <sup>this is second</sup>well and the last</td></tr></table></html>
Run Code Online (Sandbox Code Playgroud)