《Php发送Http请求,抓取网页数据方法.docx》由会员分享,可在线阅读,更多相关《Php发送Http请求,抓取网页数据方法.docx(5页珍藏版)》请在三一办公上搜索。
1、Php发送Http请求,抓取网页数据方法 Php发送Http请求,抓取网页数据方法 php发送Http请求,抓取网页数据方法 curl、file_get_contents、snoopy.class.php这三个远程页面抓取或采集中用到的工具,他们功能相当,到底有是么优缺点呢,下面逐一介绍: snoopy.class.php snoopy 是用 fsockopen 自开发的一个类,效率比较高且不需要服务器特定配置支持,在普通虚拟主机中即可使用,但是经常出问题。官方下载网址: Snoopy是一个php类,用来模拟浏览器的功能,可以获取网页内容,发送表单。 Snoopy的特点: 1、抓取网页的内容
2、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时候的最
3、好选择。 附: snoopy中文手册: 使用示例: snoopy的缺陷与CURL的强大: 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或者po
4、st数据,第三种应用就是实现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_s
5、etopt($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 doesnt honor this header but sends the whole file curl will download all of it. E.g. ignores the header. But you can (in
6、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, its only a test $len = strlen($data) + strlen
7、($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, 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);