手机版

基于curl数据采集的单页采集函数get_html的使用

时间:2021-11-20 来源:互联网 编辑:宝哥软件园 浏览:

这是一个一两天完成不了的系列,所以一一出版的大致轮廓如下:1。curl数据采集系列get _ html2的单页采集功能。curl数据采集系列get _ htmls3的多页并行采集功能。curl数据收集系列get _ matches 4的常规处理功能。curl数据收集系列的代码分离。并行控制功能web_spider单页采集是数据采集过程中最常用的功能。有时,在服务器访问受限的情况下,这种收集方法只能缓慢使用,但可以简单控制。因此,编写一个常用的curl函数调用是非常重要的。百度和网易很熟。因此,以这两个网站的首页收藏为例,说明最简单的写法:复制代码如下: $ URL=' http://www . Baidu.com ';$ ch=curl _ init($ URL);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_TIMEOUT,5);$ html=curl _ exec($ ch);if($html!==false){ echo $ html;}由于使用频繁,curl_setopt_array可以写成函数:复制代码如下:function get _ html ($ URL,$ options=array()){ $ options[curl opt _ return transfer]=true;$ options[CURLOPT _ time out]=5;$ ch=curl _ init($ URL);curl_setopt_array($ch,$ options);$ html=curl _ exec($ ch);curl _ close($ ch);if($ html===false){ return false;}返回$ html}复制代码如下: $ URL=' http://www . Baidu.com ';echo get _ html($ URL);有时,需要传递一些特定的参数来获得正确的页面。比如我们现在需要获取网易页面:复制代码如下: $ URL=' http://www . 163.com ';echo get _ html($ URL);你会看到一片空白,什么也没有。然后用curl_getinfo写一个函数看看会发生什么:复制代码如下:函数get _ info ($ URL,$ options=array()){ $ options[curl opt _ return transfer]=true;$ options[CURLOPT _ time out]=5;$ ch=curl _ init($ URL);curl_setopt_array($ch,$ options);$ html=curl _ exec($ ch);$ info=curl _ getinfo($ ch);curl _ close($ ch);返回$ info} $ URL=' http://www . 163.com ';var _ dump(get _ info($ URL));

可以看到http_code302被重定向,此时需要传递一些参数:复制的代码如下: $ URL=' http://www . 163.com ';$ options[CURLOPT _ follow location]=true;echo get_html($url,$ options);

会发现这样的页面和我们的电脑访问的页面有什么不同?看来参数还是不够。服务器在判断我们的客户端在设备上之后,返回了正常版本。似乎USERAGENT复制代码将被传输。代码如下: $ URL=' http://www . 163.com ';$ options[CURLOPT _ follow location]=true;$ options[CURLOPT _ user agent]=' Mozilla/5.0(Windows NT 6.1;RV :19.0)Gecko/20100101 Firefox/19.0 ';echo get_html($url,$ options);

现在OK页面已经出来了,这个基本的get_html函数基本可以实现这个扩展功能。当然,还有其他方法可以实现。当你对网易的网页了解清楚后,就可以简单收藏了:复制代码如下:美元URL=' http://www . 163.com/index . html ';echo get _ html($ URL);这也可以正常收集。

版权声明:基于curl数据采集的单页采集函数get_html的使用是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。