在Python中给XML.ElementTree元素的文本添加HTML标签

3 投票
1 回答
5185 浏览
提问于 2025-05-01 01:40

我正在尝试用一个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()

当你打开生成的'test.html'文件时,它会显示你输入的文本:'This is the first line <br /> and the second'。

HTML文档本身在源代码中显示了这个问题。看起来解析器把标签中的“<”和“>”符号替换成了它们的HTML表示形式:

    <!--Extraneous code removed-->
<td>This is the first line %lt;br /&gt; and the second</td>

显然,我的目的是让文档处理这个标签本身,而不是把它显示为文本。我不确定是否有不同的解析器选项可以传递来解决这个问题,或者我是否应该使用其他方法。如果使用其他模块(比如lxml)能解决问题,我也愿意尝试。我主要使用内置的XML模块是为了方便。

我唯一找到的有效方法是在写入文件之前,用re替换最终字符串:

tree = ET.tostring(root)
tree = re.sub(r'&lt;','<',tree)
tree = re.sub(r'&gt;','>',tree)

这样可以解决问题,但感觉应该通过在xml中使用不同的设置来避免这种情况。有什么建议吗?

暂无标签

1 个回答

6

你可以使用 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>

顺便提一下,如果想在 <td> 标签内包含 <sup></sup> 并添加文本,使用 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>

撰写回答