snoopy php网页抓取工具(snoopy()、file_get_contents(.class.phpsnoopy)
优采云 发布时间: 2022-02-05 15:08snoopy php网页抓取工具(snoopy()、file_get_contents(.class.phpsnoopy)
curl()、file_get_contents()、snoopy.class.php,这三个用于远程页面爬取或者采集的工具,它们的功能是等价的,各自的优缺点是什么,下面介绍一下:
史努比类.php
Snoopy 是使用 fsockopen 的自研类,效率高,不需要服务器特定的配置支持。可以在普通的虚拟主机上使用,但是经常会出现问题。官方下载地址:
Snoopy是一个模拟浏览器功能的php类,可以获取网页内容和发送表单。
史努比的特点:
1、获取网页内容fetch
2、获取网页的文本内容(去掉HTML标签) fetchtext
3、 抓取网页链接,form fetchlinks fetchform
4、支持代理主机
5、支持基本的用户名/密码认证
6、支持设置user_agent、referer(来)、cookies和header内容(头文件)
7、支持浏览器重定向,可以控制重定向深度
8、 可以将网页中的链接扩展成高质量的url(默认)
9、提交数据并获取返回值
10、支持跟踪HTML帧
11、支持重定向时传递cookie
需要php4或更高版本就足够了。既然是php的一个类,就不需要扩展支持了。服务器不支持 curl 时的最佳选择。
随附的:
史努比中文说明书:
使用示例:
史努比的缺陷和 CURL 的威力:
文件获取内容()
file_get_contents 是 fsockopen 函数的简单封装,效率稍低,但是抓取成功率很高,所以我一般在 snoopy 有问题的时候给他打电话。5.0.0 增加了对context的支持,有了context,他还可以发送header信息,自定义user agent,referer,cookies都有。5.1.0 添加了 offset 和 maxlen 参数以只读部分文件。
卷曲()
curl一般用于爬取网页,二是获取或发布数据,三是在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);
使用教程地址: