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

Python LXML:获取子元素之间的文本,python,html,lxml,Python,Html,Lxml,我有一个结构糟糕的html模板,其中我的元素包含多个元素(p、figure、a等),但中间还有原始文本。如何访问所有这些文本片段,并在适当的位置编辑它们(我需要的是用标记替换所有$$code$$) section.text和section.tail都返回空字符串…检查紧靠文本前面的完整标记的.tail。因此,在ABCDE中,两个元素的尾部将包含C和E 例如: from lxml import etree root = etree.fromstring('<root><sect

我有一个结构糟糕的html模板,其中我的
元素包含多个元素(p、figure、a等),但中间还有原始文本。如何访问所有这些文本片段,并在适当的位置编辑它们(我需要的是用标记替换所有
$$code$$

section.text
section.tail
都返回空字符串…

检查紧靠文本前面的完整标记的
.tail
。因此,在
AB

CD

E
中,两个
元素的
尾部将包含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))
从lxml导入etree
root=etree.fromstring('AB

CD

E')) 对于root.find('section')中的第_子节: section\u child.tail=section\u child.tail.lower() 打印(etree.tounicode(根))
结果:

AB

cD

e
我从我发布的问题的答案中学到:

从lxml导入etree
xml='aaaa1bbbaaa2cccaaaa3'
element=etree.fromstring(xml)
对于element.xpath('text()')中的文本:
xml=xml.replace(f'>{text}{text.upper()}
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()}<')