簡體   English   中英

獲取href的Xpath表達式。 不只是錨文本

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

試着學習它的xpath表達式。 我找到了一個代碼片段,並稍微調整了一下。 我想要做的是獲取頁面上的每個鏈接。

$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 />";
}

但現在我抓住了錨文本。 我想要href部分。 也許兩者都有。 我究竟做錯了什么?

要獲取href,您必須訪問節點的attributes屬性

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

用途

//a/@href

不需要額外的代碼(除了對此表達式的評估)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM