Я хочу получить следующие встроенные текстовые строки из корневого элемента.
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
возвращает только «text-first», включая новые строки
>>> 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
частей от этого?
Есть идеи? Спасибо!