簡體   English   中英

PHP Dom抓取大量數據

[英]PHP Dom Scraping large amount of data

我必須從8000頁x每頁25條記錄中收集一些數據。 大約有200.000條記錄。 問題是服務器在一段時間后拒絕了我的請求。 盡管我聽說它運行起來很慢,但是我使用simple_html_dom作為抓取的庫。 這是示例數據:

<table>
<tr>
<td width="50%" valign="top" style="font-size:12px;border-bottom:1px dashed #a2a2a2;">Data1</td>
<td width="50%" valign="top" style="font-size:12px;border-bottom:1px dashed #a2a2a2;">Data2</td>
</tr>
<tr>
<td width="50%" valign="top" style="font-size:12px;border-bottom:1px dashed #a2a2a2;">Data3</td>
<td width="50%" valign="top" style="font-size:12px;border-bottom:1px dashed #a2a2a2;">Data4</td>
</tr>
</table>

而php抓取腳本是:

<?php

$fileName = 'output.csv';

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");

$fh = @fopen('php://output', 'w');


ini_set('max_execution_time', 300000000000);

include("simple_html_dom.php");

for ($i = 1; $i <= 8846; $i++) {

    scrapeThePage('url_to_scrape/?page=' . $i);
    if ($i % 2 == 0)
        sleep(10);

}

function scrapeThePage($page)
{

    global $theData;


    $html = new simple_html_dom();
    $html->load_file($page);

    foreach ($html->find('table tr') as $row) {
        $rowData = array();
        foreach ($row->find('td[style="font-size:12px;border-bottom:1px dashed #a2a2a2;"]') as $cell) {
            $rowData[] = $cell->innertext;

        }

        $theData[] = $rowData;
    }
}

foreach (array_filter($theData) as $fields) {
    fputcsv($fh, $fields);
}
fclose($fh);
exit();

?>

如您所見,我在for循環中添加了10秒的睡眠間隔,因此我不會對服務器施加壓力。 當它提示我下載CSV時,其中包含以下幾行:

警告 :file_get_contents(url_to_scrape /?page = 8846):無法打開流:HTTP請求失敗! HTTP / 1.0 500內部服務器錯誤致命錯誤 :在第1113行的D:\\ www \\ htdocs \\ ucmr \\ simple_html_dom.php中的非對象上調用成員函數find()

8846頁面確實存在,它是腳本的最后一頁。 頁碼在上述錯誤中有所不同,因此有時例如在800頁會出現錯誤。 有人可以讓我知道在這種情況下我在做什么錯。 任何意見將是有益的。

致命錯誤可能是因為$html$row不是對象,它變為null 您應該始終嘗試檢查對象是否正確創建。 也許還有方法$html->load_file($page); 如果加載頁面失敗,則返回false。

也要熟悉instanceof有時變得很有幫助。

另一個編輯:您的代碼完全沒有數據驗證。 沒有地方可以檢查未初始化的變量,已卸載的對象或執行有錯誤的方法。 您應該始終在代碼中使用這些代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM