您的位置:首页 > 编程语言 > PHP开发

php发送Http请求,抓取网页数据方法(cURL,file_get_contents,snoopy)

2014-03-10 10:55 916 查看
php发送Http请求,抓取网页数据方法(cURL,file_get_contents,snoopy)

curl()、file_get_contents()、snoopy.class.php这三个远程页面抓取或采集中用到的工具,他们功能相当,到底有是么优缺点呢,下面逐一介绍:

snoopy.class.php

snoopy 是用 fsockopen 自开发的一个类,效率比较高且不需要服务器特定配置支持,在普通虚拟主机中即可使用,但是经常出问题。官方下载网址:http://sourceforge.net/projects

Snoopy是一个php类,用来模拟浏览器的功能,可以获取网页内容,发送表单。
Snoopy的特点:
1、抓取网页的内容 fetch
2、抓取网页的文本内容 (去除HTML标签) fetchtext
3、抓取网页的链接,表单 fetchlinks fetchform
4、支持代理主机
5、支持基本的用户名/密码验证
6、支持设置 user_agent, referer(来路), cookies 和 header content(头文件)
7、支持浏览器重定向,并能控制重定向深度
8、能把网页中的链接扩展成高质量的url(默认)
9、提交数据并且获取返回值
10、支持跟踪HTML框架
11、支持重定向的时候传递cookies
要求php4以上就可以了,由于本身是php一个类,无需扩支持,服务器不支持curl时候的最好选择。

附:

snoopy中文手册:http://wenku.baidu.com/view/a2110c2a192e45361066f53a.html
使用示例:http://outofmemory.cn/code-snippet/2480/php-usage-Snoopy-class-php-do-http-get-post-request
snoopy的缺陷与CURL的强大:http://www.neatstudio.com/show-1047-1.shtml

file_get_contents()

file_get_contents 是 fsockopen 功能的简单打包,效率稍低些,但是抓取成功率很高,所以在 snoopy 出问题的时候我一般那他来。5.0.0 添加了对 context 的支持,有了context,他也可以发送 header 信息,自定义用户 agent, referer, cookies 都不在话下。5.1.0 添加了 offset 和 maxlen 参数,可以只读文件的一部分内容。

curl()

curl一般用来抓取网页,第二种就是get或者post数据,第三种应用就是实现PHP的多线程任务。

功能最强大,几乎可以模拟浏览器的各个方面,几乎可以以假乱真。效率也很高,支持多线程,不过需要开启下 curl 扩展。

cURL是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP、FTP、TELNET等。PHP也支持cURL库,我们常常用来远程页面抓取和采集。

也支持断点续传Range的代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.spiegel.de/');
curl_setopt($ch, CURLOPT_RANGE, '0-500');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
/**
*But as noted before if the server doesn't honor this header but sends the whole file curl will download all of it. E.g. http://www.php.net ignores the header. But you can (in addition) set a write function callback and abort the request when more data is received, e.g.
* php 5.3+ only
* use function writefn($ch, $chunk) { ... } for earlier versions
*/
$writefn = function($ch, $chunk) {
static $data='';
static $limit = 500; // 500 bytes, it's only a test
$len = strlen($data) + strlen($chunk);
if ($len >= $limit ) {
$data .= substr($chunk, 0, $limit-strlen($data));
echo strlen($data) , ' ', $data;
return -1;
}
$data .= $chunk;
return strlen($chunk);
};
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.php.net/');
curl_setopt($ch, CURLOPT_RANGE, '0-500');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $writefn);
$result = curl_exec($ch);
curl_close($ch);


使用教程地址:
http://stackoverflow.com/questions/2032924/how-to-partially-download-a-remote-file-with-curl
http://cn2.php.net/manual/zh/ref.curl.php
http://www.360weboy.com/php/page1/curl.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐