Xpath从平面HTML层次结构中获取元素

时间:2014-07-01 16:48:20

标签: php xpath

HTML结构:

<div class="title">
    <h1>Some title</h1>
</div>    
<div class="row">something</div>

... (repeats the same structure)

<div class="title">
    <h1>Another title</h1>
</div>    
<div class="row anotherclass">1 something</div>
<div class="row">2 something</div>
<div class="row">3 something</div>

<div class="title">
    <h1>Some title</h1>
</div>    
<div class="row">something</div>

如何获取前一个标题(h1)与我的$search匹配的所有div(带有“row”类“)?

我现在所拥有的(不适用于最后一个元素,也不会停留在下一个标题):

//div[child::h1[contains(text(), "<?php echo $search ?>")]]
/following-sibling::div[contains(concat(" ", normalize-space(@class), " "), " title ")]
/preceding-sibling::div[contains(concat(" ", normalize-space(@class), " "), " row ")]

如果我搜索“其他标题”,则输出应为:

<div class="row anotherclass">1 something</div>
<div class="row">2 something</div>
<div class="row">3 something</div>

1 个答案:

答案 0 :(得分:0)

这是一个很长的问题:

//div[contains(concat(" ",@class," ")," row ")][preceding-sibling::div[contains(concat(" ",@class," ")," title ")][1][contains(h1,"<?php echo $search ?>")]]

我将它分成几部分:

你想要所有具有类行的div ...

//div[contains(concat(" ",@class," ")," row ")]

第一个前一个兄弟与一个类标题......

[preceding-sibling::div[contains(concat(" ",@class," ")," title ")][1]

有一个包含搜索查询的h1

[contains(h1,"<?php echo $search ?>")]]