我想从根元素获取以下内联文本字符串。
from lxml import etree
root = root = etree.fromstring(
'''<p>
text-first
<span>
Child 1
</span>
text-middle
<span>
Child 2
</span>
text-last
</p>''')
root.text
仅返回“文本优先”,包括换行符
>>> build_text_list = etree.XPath("//text()")
>>> texts = build_text_list(root)
>>>
>>> texts
['\n text-first\n ', '\n Child 1\n ', '\n text-middle\n ', '\n Child 2\n ', '\n text-last\n']
>>>
>>> for t in texts:
... print t
... print t.__dict__
...
text-first
{'_parent': <Element p at 0x10140f638>, 'is_attribute': False, 'attrname': None, 'is_text': True, 'is_tail': False}
Child 1
{'_parent': <Element span at 0x10140be18>, 'is_attribute': False, 'attrname': None, 'is_text': True, 'is_tail': False}
text-middle
{'_parent': <Element span at 0x10140be18>, 'is_attribute': False, 'attrname': None, 'is_text': False, 'is_tail': True}
Child 2
{'_parent': <Element span at 0x10140be60>, 'is_attribute': False, 'attrname': None, 'is_text': True, 'is_tail': False}
text-last
{'_parent': <Element span at 0x10140be60>, 'is_attribute': False, 'attrname': None, 'is_text': False, 'is_tail': True}
>>>
>>> root.xpath("./p/following-sibling::text()") # following https://stackoverflow.com/a/39832753/1677041
[]
那么,如何从中获取 text-first/middle/last
部分?
最佳答案
etree 完全有能力做到这一点:
from lxml import etree
root: etree.Element = etree.fromstring(
'''<p>
text-first
<span>
Child 1
</span>
text-middle
<span>
Child 2
</span>
text-last
</p>''')
print(
root.text,
root[0].tail,
root[1].tail,
)
所有元素都是其子元素的列表,因此这里的索引指的是 2 <span>
元素。任何元素的 tail 属性都包含紧接在该元素之后的文本。
它当然会包含换行符,因此您可能需要 strip() 结果:root.text.strip()
关于python - 如何使用 Python 从 lxml 元素获取原始文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335885/