php 网络爬虫2种方法
1,通过curl进行抓取再进行写入文件当中:
$curlobj = curl_init(); // 初始化
curl_setopt($curlobj, CURLOPT_URL, "https://www.baidu.com"); // 设置访问网页的URL
curl_setopt($curlobj, CURLOPT_RETURNTRANSFER, true); // 执行之后不直接打印出来
$output=curl_exec($curlobj); // 执行
curl_close($curlobj); // 关闭cURL
file_put_contents('dos.html',$output);
echo $output;
2,通过file_get_contents函数进行获取网页数据
$file = file_get_contents("https://www.baidu.com");
$new_file = "C:/xampp/htdocs/docs1";
if(!file_exists($new_file)){
@mkdir($new_file,'0777',true);
}
$open = fopen($new_file.'/d1.html','w+');
fwrite($open,$file);
fclose($open);
第二种也可以改成:
$file = file_get_contents("https://www.baidu.com");
$new_file = "C:/xampp/htdocs/docs1/d2.html";
file_put_contents($new_file,$file);
file_get_contents/stream_get_contents与curl对比
php中file_get_contents与curl性能比较分析一文中有详细的对比分析,主要的对比现在列下来:
– fopen /file_get_contents 每次请求都会重新做DNS查询,并不对 DNS信息进行缓存。但是CURL会自动对DNS信息进行缓存。对同一域名下的网页或者图片的请求只需要一次DNS查询。这大大减少了DNS查询的次数。所以CURL的性能比fopen /file_get_contents 好很多。
-
fopen /file_get_contents 在请求HTTP时,使用的是http_fopen_wrapper,不会keeplive。而curl却可以。这样在多次请求多个链接时,curl效率会好一些。
-
fopen / file_get_contents 函数会受到php.ini文件中allow_url_open选项配置的影响。如果该配置关闭了,则该函数也就失效了。而curl不受该配置的影响。
-
curl 可以模拟多种请求,例如:POST数据,表单提交等,用户可以按照自己的需求来定制请求。而fopen / file_get_contents只能使用get方式获取数据。
可以参考 http://blog.csdn.net/future_todo/article/details/52781218