LXML:获取元素子元素之间的文本

LXML: get text inbetween elements children

我的 html 模板结构不佳,其中我的 <section> 元素包含多个元素(p、图形、a 等),但中间还包含原始文本。我怎样才能访问所有这些文本片段,并就地编辑它们(我需要用标签替换所有 $$code$$?) section.textsection.tail return 都是空字符串...

检查紧接在文本之前的完整标记的 .tail。因此,在 <section>A<p>B</p>C<p>D</p>E</section> 中,两个 <p> 元素的 .tail 将包含 C 和 E。

示例:

from lxml import etree

root = etree.fromstring('<root><section>A<p>B</p>C<p>D</p>E</section></root>')

for section_child in root.find('section'):
    section_child.tail = section_child.tail.lower()

print(etree.tounicode(root))

结果:

<root><section>A<p>B</p>c<p>D</p>e</section></root>

我从我发布的问题的答案中了解到:Parse XML text in between elements within a root element

from lxml import etree


xml = '<a>aaaa1<b>bbbb</b>aaaa2<c>cccc</c>aaaa3</a>'
element = etree.fromstring(xml)
for text in element.xpath('text()'):
    xml = xml.replace(f'>{text}<', f'>{text.upper()}<')

对此的一个担忧是 xml 中的 CDATA,但我想这对 html 来说不是问题。