這取決於請求頁面的標記,這裏的例子用於獲取關於亞馬遜的價格:
<?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。如果不是,他們不希望你抓住任何東西。以這種方式解析並不可靠,所請求頁面的標記可能每秒都會改變(您也可能爲漏洞利用開啓一扇門)。它也可能不合法。
如果您特別指大型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
所以,跳過這一點,並通過其他所有圖像,包括這一個。那麼我就可以篩選那些沒有任何信息的元素。 – 2011-05-24 10:47:03
您爲什麼要屏蔽該網站而不是使用Amazon API? – Gordon 2011-05-24 10:54:07