在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>
答案 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:']