您的位置:首页 > 其它

【技术宅5】抓去网页数据的3种方法

2014-09-21 19:34 106 查看
抓去网页数据无非就两步:1、抓取;2:分析

抓取分几种情况:1、普通字符串,就是普通网页源码,用file_get_contents或curl抓取,2、有序数据如xml,可以用simplexml_load_file抓取

分析:如果是第二种情况,就按照xml数据来遍历处理好了。 如果是第一种情况,用preg_match来匹配目标数据

1.使用file_get_contents

$url = "http://www.34ways.com";

$contents = file_get_contents($url);

//如果出现中文乱码使用下面代码

//$getcontent = iconv("gb2312", "utf-8",$contents);

echo $contents;

2.使用curl

//初始化一个cURL对象

$ch = curl_init();

//设置抓取的URL

$url = "http://www.34ways.com";

curl_setopt($ch, CURLOPT_URL, $url);

//设置header

curl_setopt($ch,CURLOPT_HEADER,1);

//设置参数,要求结果保存到字符串中还是输出到屏幕上

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//设置参数

$timeout = 5;

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

//在需要用户检测的网页里需要增加下面两行

//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD);

//允许curl,请求网页

$contents = curl_exec($ch);

//关闭请求

curl_close($ch);

//输出数据

echo $contents;

3.使用fopen->fread->fclose

$handle = fopen ("http://www.34ways.com", "rb");

$contents = "";

do {

$data = fread($handle, 1024);

if (strlen($data) == 0) {

  break;

}

$contents .= $data;

} while(true);

fclose ($handle);

echo $contents;

最后提醒几点:

  1.使用file_get_contents和fopen必须空间开启allow_url_fopen。

方法:编辑php.ini,设置allow_url_fopen =On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。

  2.使用curl必须空间开启curl。

方法:windows下修改php.ini,将extension=php_curl.dll前面的分号去掉,而且需要拷贝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安装curl扩展。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: