2016-05-18 170 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),它工作 –