【发布时间】:2016-03-28 16:32:49
【问题描述】:
我必须从网站上获取一些用户参数。我可以这样做,因为每个用户都有一个唯一的 ID,我可以通过 URL 搜索用户:
所以我在 for() 循环中添加了这个 URL,我试图得到 500 个结果:
<?php
$start = time();
$results = array();
for($i=0; $i<= 500; $i++)
{
$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://page.com/search_user.php?uid='.$i);
curl_setopt($c, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; pl; rv:1.9.1.2) Gecko/20090729 desktopsmiley_2_2_5643778701369665_44_71 DS_gamingharbor Firefox/3.5.2 (.NET CLR 3.5.30729)');
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$p = curl_exec($c);
curl_close($c);
if ( preg_match('"<span class=\"uname\">(.*?)</span>"si', $p, $matches) )
{
$username = $matches[1];
}
else
{
continue;
}
preg_match('"<table cellspacing=\"0\">(.*?)</table>"si', $p, $matches);
$comments = $matches[1];
preg_match('"<tr class=\"pos\">(.*?)</tr>"si', $comments, $matches_pos);
preg_match_all('"<td>([0-9]+)</td>"si', $matches_pos[1], $matches);
$comments_pos = $matches[1][2];
preg_match('"<tr class=\"neu\">(.*?)</tr>"si', $comments, $matches_neu);
preg_match_all('"<td>([0-9]+)</td>"si', $matches_neu[1], $matches);
$comments_neu = $matches[1][2];
preg_match('"<tr class=\"neg\">(.*?)</tr>"si', $comments, $matches_neg);
preg_match_all('"<td>([0-9]+)</td>"si', $matches_neg[1], $matches);
$comments_neg = $matches[1][2];
$comments_all = $comments_pos+$comments_neu+$comments_neg;
$about_me = 0;
if ( preg_match('"<span>O mnie</span>"si', $p) )
{
$about_me = 1;
}
$results[] = array('comments' => $comments_all, 'about_me' => $about_me, 'username' => $username);
}
echo 'Generated in: <b>'.(time()-$start).'</b> seconds.<br><br>';
var_dump($results);
?>
最后我得到了结果: - 一切都在 135 秒内生成。
然后我将 curl 替换为 file_get_contents(),得到:155 秒。
获得此结果的方法是否比 curl 更快?我必须从另一个页面获得 20.000.000 个结果,而 135 秒对我来说太长了。
谢谢。
【问题讨论】:
-
这是每天都会发生的事情还是只是偶尔发生?
-
一次性。最后,我想使用 CRON 启动此脚本并按时间部分获取所有结果(20.000.000)(500 个结果中断 1 秒)..
标签: php curl optimization web-crawler urlfetch