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

2024-04-24 08:13:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个结构糟糕的html模板,其中我的<section>元素包含多个元素(p、figure、a等),但中间也有原始文本。我如何访问所有这些文本片段,并在适当的地方编辑它们(我需要的是用标记替换所有$$code$$section.textsection.tail都返回空字符串。。。在


Tags: 字符串text标记文本模板元素编辑html
2条回答

检查紧靠文本前面的完整标记的.tail。因此,在<section>A<p>B</p>C<p>D</p>E</section>中,两个<p>元素的{}将包含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))

结果:

^{pr2}$

我从我发布的问题中得到了答案: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的问题。在

相关问题 更多 >