簡體   English   中英

cURL和XPath顯示href錨文本?

[英]cURL & XPath to display href anchor text?

以下PHP代碼使用cURL,XPath並在特定頁面($ target_url)上顯示所有鏈接。

**我想做的是在提供網站價值時弄清楚如何僅在給定頁面上顯示錨文本(href中的鏈接詞)。

例如,...我想搜索“ randomwebsite.com”以查看是否有與我的target_url(例如ebay.com)的鏈接,並僅顯示“拍賣網站”的錨文本。

http://www.ebay.com'>拍賣網站


<?php


$target_url = "http://www.ebay.com";
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';

// make the cURL request to $target_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html= curl_exec($ch);
if (!$html) {
    echo "<br />cURL error number:" .curl_errno($ch);
    echo "<br />cURL error:" . curl_error($ch);
    exit;
}

// parse the html into a DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->query('/html/body//a');

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    echo "<br />Link: $url";
}

?>

您將在示例循環中使用$href->nodeValue獲得文本。 但這並不能真正說明您是圖像標簽還是類似標簽的情況,但是我想這正是您的具體要求。

不確定我是否明白您的要求...但是也許這是您想要實現的?

$url_matches = array('www.ebay.com' => 'Auction Site', 
                     'www.google.com' =>'Search Engine'
               );

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    if (in_array($url, $url_matches)) {
       $url = $url_matches[$url]; 
    }    
    echo "<br />Link: $url";
}

暫無
暫無

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

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