考虑这个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
元素我为它创建,它包括之后的文本等连接大量的文字我不想联系的。
我原以为文本会属于包含'span'的'p'元素?文本完全在'span'元素之外。 – jorbas
@BigJord是的,它在外面,这就是为什么它叫**尾巴**。它不能属于P元素,因为它会与第一个文本冲突; “这是一些文字,后面有2个引文。” –