3

DOMXPath$html->query('//p[@class="myclass"]/a')->item(0);不工作。

这是HTML:

<p class="username">
<img src="http://static1.tryal.com/img/b.gif" onclick="lalalaa()" class="a12s_iYblt4hN_DkIt_GoiyOtu8 opsi" />
<b>
<a href="/about"><b>Lalala.</b></a>
</b>
</p>


$name = $html->query('//p[@class="username"]/a')->item(0)->nodeValue; 
//This doesn't return the name "Lalala.";

$name = $html->query('//p[@class="username"]')->item(0)->nodeValue; 
//This works just fine.

为什么这棵树不工作?我打错了吗?

非常感谢您提前。

4

2 回答 2

3

您指定的 xpath 没有提供任何结果(或者没有准确的元素的结果)。您可以通过不让b元素滑过来解决此问题:

$name = $html->query('//p[@class="username"]/b/a')->item(0)->nodeValue; 
                                            ^^^

或者不从更深的地方a创建直接/直接子代( xpath中的双斜杠的后代):p//

$name = $html->query('//p[@class="username"]//a')->item(0)->nodeValue; 
                                            ^^
于 2011-07-02T13:43:27.320 回答
1

尝试

$name = $html->query('//p[@class="username"]//a')->item(0)->nodeValue;

你正在寻找(单斜杠)'p'的'a'孩子,而你想要我理解的是(双斜杠)'p'的'a'后代

于 2011-07-02T13:48:35.293 回答