0

我正在尝试从网站抓取中获取名称、地址和位置。它只有一个页面,除此之外不需要任何其他内容。我正在使用下面的代码。

<?php

include 'simple_html_dom.php';

$html = "http://www.phunwa.com/phone/0191/2604233";
$dom = new DomDocument();
$dom->loadHtml($html);
$xpath = new DomXpath($dom);
$div = $xpath->query('//*[@class="address-tags"]')->item(0);
for($i=0; $i < $div->length; $i++ )
    {

        print "nodename=".$div->item( $i )->nodeName;
        print "\t";
         print "nodevalue : ".$div->item( $i )->nodeValue;
         print "\r\n";
            echo $link->getElementsByTagName("<p>");
    }
?>

该网站的html源代码是

 <div class="address-tags">
            <p><strong>Name:</strong> RAJ GOPAL SINGH</p>
            <p><strong>Address:</strong> R/O BARNAI NETARKOTHIAN, P.O.MUTHI TEH.&amp; DISTT.JAMMU,X, 181206</p>
            <p><strong>Location:</strong> JAMMU, Jammu &amp; Kashmir, India</p>
            <p><strong>Other Numbers:</strong> <a href="/phone/191/2604233">01912604233</a> | <a href="/phone/191/2604233">+911912604233</a> | <a href="/phone/191/2604233">+91-191-2604233</a></p>

有人可以帮我获得三个属性作为输出。到目前为止,页面上没有任何内容。

非常感谢 。

4

2 回答 2

0

您应该对 XPath 查询使用以下内容:

//*[@class='address-tags']/p

因此,您正在检索作为“地址标签”父级的子级的实际段落节点。然后你可以对它们使用循环:

$nodes = $xpath->query('//*[@class="address-tags"]/p');
for ($i = 0; $i < $nodes->length; $i++) {
   echo $nodes->item($i)->nodeValue;
} 
// or just
foreach($nodes as $node) {
   echo $node->nodeValue;
}

现在您的代码正在正确获取找到的第一个 div,但是您继续将该 div 视为从 xpath 查询返回的 DOMNodeList,这是不正确的。->item()返回一个没有->item()方法的 DOMNode 对象。

于 2013-04-26T17:19:00.657 回答
0

你需要$dom->load($html);而不是$dom->loadHtml($html);. 这样做之后,你会;发现您的 html 格式不正确,因此请$xpath留空。

也许尝试类似:

$html = file_get_contents('http://www.phunwa.com/phone/0191/2604233');

$name = preg_replace('/(.*)(<p><strong>Name:<\/strong> )([^<]+)(<\/p>)(.*)/mis','$3',$html);
$address = preg_replace('/(.*)(<p><strong>Address:<\/strong> )([^<]+)(<\/p>)(.*)/mis','$3',$html);
$location = preg_replace('/(.*)(<p><strong>Location:<\/strong> )([^<]+)(<\/p>)(.*)/mis','$3',$html);
$othernumbers = preg_replace('/(.*)(<p><strong>Other Numbers:<\/strong> )(.*)/mis','$3',$html);
list($othernumbers,$trash)= preg_split('/<\/p>/mis',$othernumbers,0);
echo 'name: '.$name.'<br>address: '.$address.'<br>location: '.$location.'<br>other numbers: '.$othernumbers;
exit;
于 2013-04-26T21:23:06.013 回答