2011-05-24 99 views
0
<?php 
$htmlget = new DOMDocument(); 

@$htmlget->loadHtmlFile(http://www.amazon.com); 

$xpath = new DOMXPath($htmlget); 
$nodelist = $xpath->query("//img/@src"); 

foreach ($nodelist as $images){ 
    $value = $images->nodeValue; 
} 
?> 

我得到的所有图像,但我如何获得图像相同的元素周围的信息?例如,在amazon.com上,theres a kindle。我现在有图片,但需要围绕着这样的信息如价格说明... 感谢domdocument如何获得信息和图片

+0

如果您特别指大型kindle-image,那么将没有办法,因为您看到的价格是图像的一部分,并且在DOM内不可用。 http://g-ecx.images-amazon.com/images/G/01/kindle/merch/shasta-de-redirect-475x313._V182303681_.png – 2011-05-24 10:44:13

+0

所以,跳过这一点,并通过其他所有图像,包括这一个。那么我就可以筛选那些没有任何信息的元素。 – 2011-05-24 10:47:03

+1

您为什么要屏蔽该网站而不是使用Amazon API? – Gordon 2011-05-24 10:54:07

回答

1

这取决于请求页面的标记,这里的例子用于获取关于亚马逊的价格:

<?php 
     $htmlget = new DOMDocument(); 

     @$htmlget->loadHtmlFile('http://www.amazon.com'); 

     $xpath = new DOMXPath($htmlget); 
     $nodelist = $xpath->query("//img/@src"); 

     foreach ($nodelist as $imageSrc){ 

     //fetch images with a parent node that has class "imagecontainer" 
     if($imageSrc->parentNode->parentNode->getAttribute('class')=='imageContainer') 
     { 
     //skip dummy-images 
     if(strstr($imageSrc->nodeValue,'transparent-pixel'))continue; 

     //point to the common anchestor of image and product-details 
     $wrapper=$imageSrc->parentNode->parentNode->parentNode->parentNode->parentNode; 

     //fetch the price 
     $price=$xpath->query('span[@class="red t14"]',$wrapper); 
     if($price->length) 
     { 
      echo '<br/><img src="'.$imageSrc->nodeValue.'">'.$price->item(0)->nodeValue.'<br/>'; 
     }; 
     } 
} 
?> 

但是,你不应该这样解析页面。如果他们想为您提供一些信息,那么ususally会拥有一个API。如果不是,他们不希望你抓住任何东西。以这种方式解析并不可靠,所请求页面的标记可能每秒都会改变(您也可能为漏洞利用开启一扇门)。它也可能不合法。

+0

谢谢。但亚马逊是一个例子..我希望它能够废除任何网站,并首先检索图像,然后在图像元素中的任何数据..可能是包含图像的div。价钱。说明等 – 2011-05-24 11:29:26

+2

所以你必须使用'DOMDocument :: crystalBall($ htmlget,guessWhatIWant)' – 2011-05-24 11:32:07

+0

哈哈..基本上,我想抓取任何网址,获取图像,并以某种方式获取任何信息包含在其自己的元素..它可能是一个div。例如

blah blah
2011-05-24 11:40:57