并行采集函数设计与实现
若使用前文所述的get_html()进行简单数据采集,因需逐个执行,传输时间等于所有页面下载时长的总和。假设单个页面耗时1秒,采集10个页面则需10秒。为提升效率,可利用curl提供的并行处理机制。
构建并行采集函数前,需明确目标页面的类型及所需的请求方式,从而设计出通用性较强的函数。
功能需求分析如下:
返回值定义:
应返回由每个页面HTML内容组成的数组集合。
参数传递策略:
在编写get_html()时,已知可通过options数组传递更多curl参数。因此,多页面同时采集函数也应保留这一特性,以支持灵活的参数配置。
参数类型确定:
无论是请求网页HTML还是调用互联网API接口,GET和POST请求通常针对同一页面或接口,仅参数不同。因此,参数类型设计需涵盖这两种情况。
初步设想函数签名为:get_htmls($url,$options);
$url 应为字符串类型。
$options 应为二维数组,其中每个页面的独立参数作为一个子数组存在。
然而,查阅curl手册未找到直接传递GET参数的方法,故调整方案:$url 改为数组形式,并增加一个method参数以区分请求方式。
最终确定的函数原型为 get_htmls($urls,$options = array(), $method = 'get')。代码如下: 复制代码 代码如下: function get_htmls($urls, $options = array(), $method = 'get'){ $mh = curl_multi_init(); if($method == 'get'){//get方式传值 最常用 foreach($urls as $key=>$url){ $ch = curl_init($url); $options[CURLOPT_RETURNTRANSFER] = true; $options[CURLOPT_TIMEOUT] = 5; curl_setopt_array($ch,$options); $curls[$key] = $ch; curl_multi_add_handle($mh,$curls[$key]); } }elseif($method == 'post'){//post方式传值 foreach($options as $key=>$option){ $ch = curl_init($urls); $option[CURLOPT_RETURNTRANSFER] = true; $option[CURLOPT_TIMEOUT] = 5; $option[CURLOPT_POST] = true; curl_setopt_array($ch,$option); $curls[$key] = $ch; curl_multi_add_handle($mh,$curls[$key]); } }else{ exit("参数出错!\n"); } do{ $mrc = curl_multi_exec($mh,$active); curl_multi_select($mh);//减少CPU压力 注释掉CPU压力变大 }while($active); foreach($curls as $key=>$ch){ $html = curl_multi_getcontent($ch); curl_multi_remove_handle($mh,$ch); curl_close($ch); $htmls[$key] = $html; } curl_multi_close($mh); return $htmls; } 常用的get请求是通过改变url参数来实现的,又因为我们的函数是针对数据采集的。必然是分类采集,所以网址类似于这种:
http://www.baidu.com/s?wd=shili&pn=0&ie=utf-8
http://www.baidu.com/s?wd=shili&pn=10&ie=utf-8
http://www.baidu.com/s?wd=shili&pn=20&ie=utf-8
http://www.baidu.com/s?wd=shili&pn=30&ie=utf-8
http://www.baidu.com/s?wd=shili&pn=50&ie=utf-8
上述五个页面具有规律性,仅pn值发生变化。 复制代码 代码如下: $urls = array(); for($i=1; $i<=5; $i++){ $urls[] = 'http://www.baidu.com/s?wd=shili&pn='.(($i-1)*10).'&ie=utf-8'; } $option[CURLOPT_USERAGENT] = 'Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0'; $htmls = get_htmls($urls,$option); foreach($htmls as $html){ echo $html;//这里得到html 就可以进行数据处理了 } 模拟常用的post请求:
创建一个post.php文件,内容如下: 复制代码 代码如下: if(isset($_POST['username']) && isset($_POST['password'])){ echo '用户名是: '.$_POST['username'].' 密码是: '.$_POST['password']; }else{ echo '请求错误!'; } 调用示例如下: 复制代码 代码如下: $url = 'http://localhost/yourpath/post.php';//这里是你的路径 $options = array(); for($i=1; $i<=5; $i++){ $option[CURLOPT_POSTFIELDS] = 'username=user'.$i.'&password=pass'.$i; $options[] = $option; } $htmls = get_htmls($url,$options,'post'); foreach($htmls as $html){ echo $html;//这里得到html 就可以进行数据处理了 } 至此,get_htmls函数基本实现了数据采集功能。
本次分享到此结束,如有不足之处,敬请指正。