php curl抓取网页数据(PHP的调用测试(get(get)函数(图) )

优采云 发布时间: 2021-09-12 21:06

  php curl抓取网页数据(PHP的调用测试(get(get)函数(图)

)

  PHP 的 curl 功能真的很强大。里面有个curl_multi_init函数,就是批处理任务。可以用它来实现多进程同时抓取多条记录,优化常见的网页抓取程序。

  一个简单的获取函数:

  function http_get_multi($urls){

$count = count($urls);

$data = [];

$chs = [];

// 创建批处理cURL句柄

$mh = curl_multi_init();

// 创建cURL资源

for($i = 0; $i < $count; $i ++){

$chs[ $i ] = curl_init();

// 设置URL和相应的选项

curl_setopt($chs[ $i ], CURLOPT_RETURNTRANSFER, 1); // return don't print

curl_setopt($chs[ $i ], CURLOPT_URL, $urls[$i]);

curl_setopt($chs[ $i ], CURLOPT_HEADER, 0);

curl_multi_add_handle($mh, $chs[ $i ]);

}

// 增加句柄

// for($i = 0; $i < $count; $i ++){

// curl_multi_add_handle($mh, $chs[ $i ]);

// }

// 执行批处理句柄

do {

$mrc = curl_multi_exec($mh, $active);

} while ($active > 0);

while ($active and $mrc == CURLM_OK) {

if (curl_multi_select($mh) != -1) {

do {

$mrc = curl_multi_exec($mh, $active);

} while ($mrc == CURLM_CALL_MULTI_PERFORM);

}

}

for($i = 0; $i < $count; $i ++){

$content = curl_multi_getcontent($chs[ $i ]);

$data[ $i ] = ( curl_errno($chs[ $i ]) == 0 ) ? $content : false;

}

// 关闭全部句柄

for($i = 0; $i < $count; $i ++){

curl_multi_remove_handle($mh, $chs[ $i ]);

}

curl_multi_close($mh);

return $data;

}

  下面的调用测试(get() 函数就像这里:):

  //弄很多个网页的url

$url = [

'http://www.baidu.com',

'http://www.163.com',

'http://www.sina.com.cn',

'http://www.qq.com',

'http://www.sohu.com',

'http://www.douban.com',

'http://www.cnblogs.com',

'http://www.taobao.com',

'http://www.php.net',

];

$urls = [];

for($i = 0; $i < 10; $i ++){

foreach($url as $r)

$urls[] = $r . '/?v=' . rand();

}

//并发请求

$datas = http_get_multi($urls);

foreach($datas as $key => $data){

file_put_contents('log/multi_' . $key . '.txt', $data); // 记录一下请求结果。记得创建一个log文件夹

}

$t2 = microtime(true);

echo $t2 - $t1;

echo '<br />';

//同步请求, get()函数如这里: http://www.cnblogs.com/whatmiss/p/7114954.html

$t1 = microtime(true);

foreach($urls as $key => $url){

file_put_contents('log/get_' . $key . '.txt', get($url)); // 记录一下请求结果。记得创建一个log文件夹

}

$t2 = microtime(true);

echo $t2 - $t1;

  测试结果显示出明显的差距,随着数据量的增加,差距会呈指数级扩大:

  2.4481401443481

21.68923997879

8.925509929657

24.73141503334

3.243185043335

23.384337902069

3.2841880321503

24.754415035248

3.2091829776764

29.068662881851

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线