Xpath:选择以下直到节点

时间:2012-05-04 10:36:38

标签: xpath

在Xpath中,我需要选择<p>个节点之后的<h2>DATA</h2>个节点,直到下一个<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>

1 个答案:

答案 0 :(得分:9)

这个怎么样?

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:']