为什么lxml中的这个元素包含尾部?

2024-06-16 18:57:59 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑一下这个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元素,而我得到:

^{pr2}$

为什么它在元素后面包含文本直到父元素的结尾?在

我试图使用lxml链接脚注,当我将a.insert()元素添加到我为其创建的a元素中时,它包含了后面的文本,因此链接了大量我不想链接的文本。在


Tags: text文本元素is链接htmlbodysome
2条回答

它包括元素后面的文本,因为该文本属于元素。在

如果不希望该文本属于上一个范围,则需要将其包含在其自己的元素中。但是,在将元素转换回XML时,可以避免打印此文本,并将with_tail=False作为etree.tostring()的参数。在

如果要从特定元素中移除元素tail,也可以简单地将元素tail设置为''。在

指定with_tail=False将删除尾部文本。在

print(etree.tostring(element, encoding="unicode", pretty_print=True, with_tail=False))

^{} documentation。在

相关问题 更多 >