考虑一下这个Python脚本:
from lxml import etree
html = '''
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<p>This is some text followed with 2 citations.<span class="footnote">1</span>
<span сlass="footnote">2</span>This is some more text.</p>
</body>
</html>'''
tree = etree.fromstring(html)
for element in tree.findall(".//{*}span"):
if element.get("class") == 'footnote':
print(etree.tostring(element, encoding="unicode", pretty_print=True))
期望的输出是2span
元素,而我得到:
为什么它在元素后面包含文本直到父元素的结尾?在
我试图使用lxml链接脚注,当我将a.insert()
元素添加到我为其创建的a
元素中时,它包含了后面的文本,因此链接了大量我不想链接的文本。在
它包括元素后面的文本,因为该文本属于元素。在
如果不希望该文本属于上一个范围,则需要将其包含在其自己的元素中。但是,在将元素转换回XML时,可以避免打印此文本,并将
with_tail=False
作为etree.tostring()
的参数。在如果要从特定元素中移除元素tail,也可以简单地将元素tail设置为
''
。在指定
with_tail=False
将删除尾部文本。在见^{} documentation 。在
相关问题 更多 >
编程相关推荐