2016-05-18 166 views
0

通過下面的代碼,我只得到空白頁的名稱或暱稱沒有得到回顯。我越過檢查路徑其正確仍然沒有任何迴應Xpath返回空白頁不回顯值

<?php 

$url="http://www.mans-best-friend.org.uk/dog-breeds-alphabetical-list.htm"; 

$curl_handle=curl_init(); 
curl_setopt($curl_handle, CURLOPT_URL,$url); 
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); 
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1'); 
$html = curl_exec($curl_handle); 
curl_close($curl_handle); 

$mydoc = new DOMDocument(); 

libxml_use_internal_errors(TRUE); //disable libxml errors 

if(empty($html)) die("EMPTY HTML"); 

    $mydoc->loadHTML($html); 
    libxml_clear_errors(); //remove errors for yucky html 

    $my_xpath = new DOMXPath($mydoc); 

    ////////////////////////////////////////////////////// 

    $nodes = $my_xpath->query('//*[@id="table94"]/tbody/tr/td');  

    foreach($nodes as $node) 
    { 
    $title=$my_xpath->query('p[@data-iceapc="1"]/span/a/font', $node); 
    $nickname=$my_xpath->query('p[@data-iceapc="2"]/span/a/font', $node); 
    echo $title." ".$nickname."<br>";  
    } 

?> 

如果你找不到p元素。滾動到狗名稱的部分。對於例如Affenpinscher右鍵點擊它並選擇檢查 - 它顯示p元素。

+0

如果我看看你的引用鏈接的源代碼,不存在'與'數據iceapc p'元'屬性。因此你的xpath不能匹配。 –

+0

它在那裏...滾動到狗名稱的部分.g Affenpinscher右鍵單擊它並選擇檢查...它顯示p元素 –

+0

此屬性來自此頁面上的許多跟蹤器之一。嘗試啓用某個adblock,或只是觀看curl獲得的html代碼,您將看到該屬性不是原始源代碼的一部分。 –

回答

0

首先,您必須「修復」xpath的html代碼才能正常工作,因爲它包含的錯誤太多。在這種情況下,即時通訊只提取所需的表與ID表94。

之後,您可以使用DOM對象的XPath來獲取你想要的數據:

<?php 
$url="http://www.mans-best-friend.org.uk/dog-breeds-alphabetical-list.htm"; 

$curl_handle=curl_init(); 
curl_setopt($curl_handle, CURLOPT_URL,$url); 
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); 
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1'); 
$html = curl_exec($curl_handle); 
curl_close($curl_handle); 

$html = preg_replace('/^.*(<table[^>]*id="table94">.*?<\/table>).*$/is', '\1', $html); 

$mydoc = new DOMDocument(); 
$mydoc->loadHTML($html); 

$my_xpath = new DOMXPath($mydoc); 

$nodes = $my_xpath->query('//tr');  

foreach($nodes as $node) 
{ 
    if ($my_xpath->query('td[position()=last()-1]/p/span/a/font', $node)->length > 0) { 
     echo $my_xpath->query('td[position()=last()-1]/p/span/a/font', $node)->item(0)->textContent.' '; 
     echo $my_xpath->query('td[position()=last()]/p/span/font', $node)->item(0)->textContent."<br />"; 
    } 
} 
+0

它給出的錯誤致命錯誤:不能使用DOMNodeList類型的對象作爲數組在24行.ie回波線 –

+0

我已經編輯了答案使用' item'方法而不是數組訪問。 –

+0

好吧,我剛剛用'td [position()= last() - 1]替換了'td [position()= last() - 1]/p/span/a/font',$ node)[0]/p/span/a/font',$ node) - > item(0),它工作 –