4

在 Xpath 中,我需要选择<p>节点之后的<h2>DATA</h2>节点,直到 next <h2>,所以在如下结构中:

<div class="box">
    <h2>NO</h2>
    <p>B:<span> Y</span></p>
    <h2>DATA</h2>
    <p>AA:<span> CONTENT</span></p>
    <p>AA:<span> MORE</span></p>
    <h2>NO</h2>
    <p>C:<span> Z</span></p>
    <h2>DATA</h2>
    <p>BB:<span> CONTENT</span></p>
    <p>BB:<span> MORE</span></p>
</div>

应该选择:

    <p>AA:<span> CONTENT</span></p>
    <p>AA:<span> MORE</span></p>
    <p>BB:<span> CONTENT</span></p>
    <p>BB:<span> MORE</span></p>
4

1 回答 1

10

这个怎么样?

p[preceding-sibling::h2[1][.="DATA"]]

我用于检查我提供的 xpath 的 python 测试:

>>> from lxml import etree
>>> doc = etree.XML("""<div class="box">
...     <h2>NO</h2>
...     <p>B:<span> Y</span></p>
...     <h2>DATA</h2>
...     <p>AA:<span> CONTENT</span></p>
...     <p>AA:<span> MORE</span></p>
...     <h2>NO</h2>
...     <p>C:<span> Z</span></p>
...     <h2>DATA</h2>
...     <p>BB:<span> CONTENT</span></p>
...     <p>BB:<span> MORE</span></p>
... </div>""")
>>> doc.xpath('p[preceding-sibling::h2[1][.="DATA"]]')
[<Element p at 252ef70>, <Element p at 252efc8>, <Element p at 2542050>, <Element p at 25420a8>]
>>> doc.xpath('p[preceding-sibling::h2[1][.="DATA"]]/text()')
['AA:', 'AA:', 'BB:', 'BB:']
于 2012-05-04T10:51:49.167 回答