简体   繁体   English

获取href的Xpath表达式。 不只是锚文本

[英]Xpath expression to get href. Not just anchor text

Playing around with xpath expressions trying to learn it. 试着学习它的xpath表达式。 I found a code snippet, and adjusted it a little. 我找到了一个代码片段,并稍微调整了一下。 What I'm trying to do is get every link on a page. 我想要做的是获取页面上的每个链接。

$baseurl = "http://www.example.com";
$html = file_get_contents($baseurl);

$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);


$ahrefs = $xpath->query('//a');

foreach ($ahrefs as $ahref) { 
    echo $ahref->childNodes->item(0)->nodeValue . "<br />";
}

But now I'm grabbing the anchor text. 但现在我抓住了锚文本。 I want the href part. 我想要href部分。 Maybe even both. 也许两者都有。 What am I doing wrong? 我究竟做错了什么?

要获取href,您必须访问节点的attributes属性

echo $ahref->attributes->getNamedItem("href")->nodeValue . "<br />";

Use : 用途

//a/@href

No additional code (except for the evaluation of this expression) is necessary. 不需要额外的代码(除了对此表达式的评估)。

echo $ahref->getAttribute('href') . "<br />";

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

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