2013-07-10 52 views
0

我必须从每页超过8000页x 25条记录中收集一些数据。这大约有200.000多条记录。问题在于服务器在一段时间后拒绝了我的请求。虽然我听说它很慢,但我使用simple_html_dom作为库的库。这是样本数据:PHP 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 /页= 8846):未能打开流:HTTP请求失败! HTTP/1.0 500内部服务器错误 致命错误:调用一个成员函数查找()一个非对象在d:\ WWW \ htdocs中\ ucmr \上线simple_html_dom.php

8846页面确实存在,它是脚本的最后一页。页码因上面的错误而有所不同,所以有时我会收到第800页的错误消息。 有人可以给我一个想法,我在这种情况下做错了什么。任何意见将是有益的。

回答

0

致命的可能是因为$html$row不是一个对象,它变成了null。 您应该始终尝试检查对象是否已正确创建。如果加载页面失败,也许方法$html->load_file($page);返回false。

还熟悉instanceof - 它有时变得非常有用。

另一编辑: 您的代码没有数据验证AT ALL。没有地方可以检查未初始化的变量,卸载的对象或执行错误的方法。你应该总是在你的代码中使用这些。

+0

我认为,$ html变成了空,因为远程服务器以某种方式拒绝了我的一些请求。我对前五页进行了一些测试,它将csv与前五页中包含的所有数据一起输出。 – user1584704

+0

仍然 - 您应该检查空/错,处理它们(例如 - 将不可读的页面写入文件或数据库,以便稍后再检查它们)并继续下一页不间断。 – ex3v