2011-05-24 87 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