我有一个结构很糟糕的 html 模板,其中我的
<section>
元素包含多个元素(p、figure、a 等),但中间也包含原始文本。我如何访问所有这些文本片段,并就地编辑它们(我需要的是用标签替换所有$$code$$
?)
section.text
和 section.tail
都返回空字符串...
检查紧邻文本之前的完整标记的
.tail
。因此,在 <section>A<p>B</p>C<p>D</p>E</section>
中,两个 .tail
元素的 <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))
结果:
<root><section>A<p>B</p>c<p>D</p>e</section></root>
我从我发布的问题的答案中了解到:在根元素内的元素之间解析 XML 文本
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 来说不是问题。