lxml etree获取元素之前的所有文本

时间:2015-06-24 15:14:08

标签: python xml xml-parsing lxml elementtree

如何将之前的所有文字文本中的元素分开?

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>标记,然后在该占位符处剪切字符串,但我需要与实际元素的对应关系。

1 个答案:

答案 0 :(得分:2)

可能有一种更简单的方法,但我会使用以下XPath表达式:

preceding-sibling::*/text()|preceding::text()
following-sibling::*/text()|following::text()

示例实施(绝对违反DRY原则):

def get_text_before(element):
    for item in element.xpath("preceding-sibling::*/text()|preceding-sibling::text()"):
        item = item.strip()
        if item:
            yield item

def get_text_after(element):
    for item in element.xpath("following-sibling::*/text()|following-sibling::text()"):
        item = item.strip()
        if item:
            yield item

for el in tree.findall('.//dd'):
    before = " ".join(get_text_before(el))
    after = " ".join(get_text_after(el))

    print {
        "el": el,
        "before": before,
        "after": after
    }

打印:

{'el': <Element dd at 0x10af81488>, 'after': 'before and after', 'before': 'find the text'}
{'el': <Element dd at 0x10af81200>, 'after': 'and after', 'before': 'find the text before'}