2013-08-27 42 views
0

我正嘗試從亞馬遜網址加載html文件以在Yii上使用簡單的php函數提取產品價格。 我開始使用php函數file_get_contents獲取整個文件,並且僅使用DOM從我的html文件中提取價格。如何在沒有亞馬遜API的情況下從亞馬遜網址提取價格

我正在使用DOM解析器來讀取HTML文件。它具有讀取html文件標籤的方便功能。這是解析器:

http://simplehtmldom.sourceforge.net/

在PHP分析可以amazon.com,amazon.co.uk,amazon.it,等將來此功能也將被使用的URL分析其他url與亞馬遜不同。

我創建了一個簡單的功能,即從URL中提取價格,那就是:

public function findAmazonPriceFromUrl($url) { 
    Yii::import('ext.HtmlDOMParser.*'); 
    require_once('simple_html_dom.php'); 

    $html = file_get_html($url); 
    $item = $html->getElementsById('actualPriceValue'); 
    if ($item) { 
     $price = $item[0]->firstChild()->innertext; 
    } else { 
     $item = $html->getElementsById('current-price'); 
     $price = $item[0]->innertext; 
    } 
    return $price; 
} 

file_get_html功能如下:

function file_get_html($url) { 
    $dom = new simple_html_dom(); 
    $contents = file_get_contents($url); 
    if (empty($contents) || strlen($contents) > MAX_FILE_SIZE) { 
     return false; 
    } 
$dom->load($contents); 
return $dom; 

}

我注意到一些請求(各種鏈接)後,我總是從服務器收到一個錯誤(錯誤500)。我檢查了我的apache日誌文件,但一切都很好。

亞馬遜可能會在一段時間後阻止我的請求?我該如何解決它?

在此先感謝您的幫助

+0

您請求頁面一秒多少次? –

+0

Youj可以添加另一臺用於查詢的服務器。首先嚐試在500錯誤發生時檢查頁面的內容。另外,請考慮使用他們的產品搜索api –

+0

那麼,如果你在高頻率中刪除他們的頁面,他們可能會阻止你,解決方案是使用代理或減慢你的請求 –

回答

1

我有同樣的問題,這是我的解決辦法:我再次運行腳本,如果圖像是不被解析。圖像首先在我的PHP腳本中解析,所以我檢查它是否有效,亞馬遜提供的信息。我希望它有幫助。

if($html->find('#main-image')) {  
    foreach($html->find('#main-image') as $e) { 
     echo '<span href="'. $e->src . '" class="imgblock parseimg"> 
       <img src="'. $e->src . '" class="resultimg" alt="'.$name.'" title="'.$name.'"> 
      </span> 
      <input type="hidden" name="my-item-img" value="'. $e->src . '" />'; 
    } 
} else { 
    gethtml($url,$domain); 
    die; 
} 
+0

圖片檢查並再次發送請求(當它未被解析時),您不需要輸入其他... gethtml ...用於其他對象(價格,大小...),因爲如果圖像被解析,這意味着亞馬遜給出整體頁面,沒有什麼可擔心的 –