2013-11-22 31 views
4

考虑这个Python脚本:为什么lxml中的这个元素包含尾部?

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)) 

所需的输出将是2个span元素,而不是我得到:

<span xmlns="http://www.w3.org/1999/xhtml" class="footnote">1</span> 
<span xmlns="http://www.w3.org/1999/xhtml" class="footnote">2</span>This is some more text. 

为什么它包括元素之后的文本直到父结束元件?

我试图使用LXML链接脚注,当我a.insert()span元素插入a元素我为它创建,它包括之后的文本等连接大量的文字我不想联系的。

回答

0

它包含元素之后的文本,因为该文本属于该元素。

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

如果您想将其从特定元素中移除,您还可以简单地将元素尾部设置为''

+0

我原以为文本会属于包含'span'的'p'元素?文本完全在'span'元素之外。 – jorbas

+0

@BigJord是的,它在外面,这就是为什么它叫**尾巴**。它不能属于P元素,因为它会与第一个文本冲突; “这是一些文字,后面有2个引文。” –

相关问题