php
  • parsing
  • curl
  • html-parsing
  • 2013-04-14 25 views 1 likes 
    1

    我得到了這個錯誤「致命錯誤:調用未定義的方法DOMText :: getAttribute()」與此代碼。我想捕捉鏈接的文本而不是源(我不知道它叫什麼)。有人請向我解釋我的錯誤,或告訴我一個不同的方式來做這件事嗎?這裏是我的代碼:如何獲取<a>的文本標籤使用cURL?

    <?php 
    
    $target_url = "SITE I WANT"; 
    $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->evaluate("/html/body//a/text()"); 
    
    for ($i = 0; $i < $hrefs->length; $i++) { 
        $href = $hrefs->item($i); 
        $url = $href->getAttribute('href'); 
        storeLink($url,$target_url); 
        echo "<br />Link stored: $url"; 
    } 
    $id = "12"; 
        $query = "DELETE FROM links WHERE id<=$id"; 
        if(!mysql_query($query)) 
         echo "DELETE failed: $query<br />" . 
         mysql_error() . "<br /><br />"; 
         ?> 
    
    +0

    檢查'$ hrefs'的內容。也許你應該使用'/ html/body // a',然後在每個元素上嘗試檢索它的文本。 – MatRt

    +0

    您能否提供我會這樣做的代碼?我通常都是新來的。 –

    +0

    看看@Adidi回覆,他/她正在編碼我剛剛評論過的內容 – MatRt

    回答

    0

    你去那裏:

    $document = new DOMDocument(); 
    $document->loadHTML($html); 
    $selector = new DOMXPath($document); 
    $anchors = $selector->query('/html/body//a'); 
    
    foreach($anchors as $a) { 
        $text = $a->nodeValue; 
        $href = $a->getAttribute('href'); 
        echo($text . ' : ' . $href . '<br />'); 
    
    } 
    
    +0

    非常感謝你的先生! –

    相關問題