【发布时间】:2015-09-10 21:09:16
【问题描述】:
如何将所有文本 before 与元素 after 元素分开的 etree 中的元素分开?
from lxml import etree
tree = etree.fromstring('''
<a>
find
<b>
the
</b>
text
<dd></dd>
<c>
before
</c>
<dd></dd>
and after
</a>
''')
我想要什么?在此示例中,<dd> 标记是分隔符,用于所有分隔符
for el in tree.findall('.//dd'):
我想要在它们之前和之后的所有文本:
[
{
el : <Element dd at 0xsomedistinctadress>,
before : 'find the text',
after : 'before and after'
},
{
el : <Element dd at 0xsomeotherdistinctadress>,
before : 'find the text before',
after : 'and after'
}
]
我的想法是在树中使用某种占位符,用它替换 <dd> 标记,然后在该占位符处剪切字符串,但我需要与实际元素的对应关系。
【问题讨论】:
标签: python xml xml-parsing lxml elementtree