简体   繁体   English

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

[英]DOMXPath $html->query('//p[@class=“myclass”]/a')->item(0); not working

DOMXPath $html->query('//p[@class="myclass"]/a')->item(0); DOMXPath $html->query('//p[@class="myclass"]/a')->item(0); is not working.不管用。

Here is the HTML:这是 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.

Why isn't this tree working?为什么这棵树不工作? Am I typing it wrong?我打错了吗?

Thank you very much in advance.非常感谢您提前。

The xpath you have specified didn't provide any result (or an result with no elements to be precise).您指定的 xpath 没有提供任何结果(或者没有准确的元素的结果)。 You can fix that by not letting the b element slip through:您可以通过不让b元素滑过来解决此问题:

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

or by not making a a direct/immediate child from p but somewhere deeper as well ( descendant of , double slash // in xpath):或者不a p直接/直接子代,而是在更深的地方(xpath 中的双斜杠//后代):

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

Try尝试

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

You are looking for 'a' child of (single slash) 'p', while what you want I understand is 'a' descendant of (double slash) 'p'你正在寻找(单斜杠)'p'的'a'孩子,而你想要我理解的是(双斜杠)'p'的'a'后代

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM