这是我的HTML:
<div class="content">
<div class="post">
<img class="img" src="getme"/> (<~~ retrieve this one)
<img class="img" src="notme"/>
<img class="img" src="notme"/>
</div>
<div class="post">
<img class="img" src="getme"/> (<~~ retrieve this one)
<img class="img" src="notme"/>
<img class="img" src="notme"/>
</div>
</div>
这是我用过的XPATH:
//div[@class="content"]//div[@class="post"]//@src[1]
(//div[@class="content"]//div[@class="post"]//@src)[1]
我想要完成的只是检索我明确声明要检索的那些。当我使用第二个Xpath((//div[@class="content"]//div[@class="post"]//@src)[1]
)时,它只提供第一个img src,就是它(不是每个div post元素的第一个)
答案 0 :(得分:2)
使用以下xpath查询:
//div[@class="post"]/img[1]/@src
示例:
$html = <<<EOF
<div class="content">
<div class="post">
<img class="img" src="getme"/> (<~~ retrieve this one)
<img class="img" src="notme"/>
<img class="img" src="notme"/>
</div>
<div class="post">
<img class="img" src="getme"/> (<~~ retrieve this one)
<img class="img" src="notme"/>
<img class="img" src="notme"/>
</div>
</div>
EOF;
$doc = new DOMDocument();
@$doc->loadHTML($html);
$selector = new DOMXPath($doc);
foreach($selector->query('//div[@class="post"]/img[1]/@src') as $node) {
var_dump($node->nodeValue);
}
输出:
string(5) "getme"
string(5) "getme"