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