gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:55 24 4
gpt4 key购买 nike

我正在尝试使用 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”文件时,它会显示与输入完全相同的文本字符串:“这是第一行
和第二行”。

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 中使用不同的设置来避免这种情况。 .有什么建议吗?

最佳答案

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

作为旁注,包括 <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>

关于python - 在 Python 中将 html 标签添加到 XML.ElementTree 元素的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com