php可以抓取网页数据吗(htmlsnoopy()、file_get_contents())

优采云 发布时间: 2022-02-19 10:16

  php可以抓取网页数据吗(htmlsnoopy()、file_get_contents())

  curl()、file_get_contents()、snoopy.class.php是远程页面爬取或采集中使用的三个工具。它们的功能至关重要。它们的优点和缺点是什么?我们来一一介绍:html

  snoopy.class.phpweb

  Snoopy 是使用 fsockopen 的自研类,效率高,不需要服务器特定的配置支持。可以在普通的虚拟主机上使用,但是经常会出现问题。官方下载地址:浏览器

  Snoopy是一个模拟浏览器功能的php类,可以获取网页内容和发送表单。服务器

  史努比的特点:饼干

  一、 抓取网页内容获取多线程

  二、获取网页文本内容(去掉HTML标签)fetchtext框架

  三、抓取网页的链接,form fetchlinks fetchformcurl

  四、支持代理主机ide

  五、支持基本的用户名/密码认证

  六、支持设置user_agent、referer(来)、cookies和header内容(头文件)

  七、支持浏览器重定向,可以控制重定向深度

  八、 可以将网页中的链接扩展为高质量的url(默认)

  九、提交数据并获取返回值

  十、支持跟踪 HTML 帧

  10一、支持重定向时传递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);

  使用教程地址:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线