简体   繁体   中英

Xpath expression to get href. Not just anchor text

Playing around with xpath expressions trying to learn it. 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. 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 />";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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