不要走开,接下来就分别来看看这六种方法,你掌握了几个?
1.file()函数
2.使用file_get_contents方法实现,比较简单。
使用 file_get_contents 和fopen必须空间开启 allow_url_fopen 。方法:编辑PHP.ini,设置 allow_url_fopen = On,allow_url_fopen 关闭时fopen和 file_get_contents 都不能打开远程文件。
$url="[http://news.sina.com.cn/c/nd/2016-10-23/doc-ifxwztru6951143.shtml](http://news.sina.com.cn/c/nd/2016-10-23/doc-ifxwztru6951143.shtml)"; $html=file_get_contents($url); 如果出现中文乱码使用下面代码` //$getcontent = iconv("gb2312","utf-8",$html); echo"<textarea style='width:800px;height:600px;'>".$html."</textarea>";
3.fopen()->fread()->fclose()模式 ,目前还没用过,看到了就先记下了
4.使用curl实现(本人一般使用这个)。
使用 curl 必须空间开启 curl 。方法:windows下修改 PHP.ini ,将 extension=PHP_curl.dll 前面的分号去掉,而且需 要拷贝 ssleay32.dll 和 libeay32.dll 到 C:\WINDOWS\system32 下;Linux下要安装 curl 扩展。
<?header("Content-Type: text/html;charset=utf-8"); date_default_timezone_set('PRC'); $url = "https://***********ycare";要爬取的网址 $res = curl_get_contents(curl封装方法 preg_match_all('/<script>(.*?)<\/script>/',1)">$res,1)">$arr_all);这个网页中数据通过js包过来,所以直接抓js就可以 preg_match_all('/"id"\:"(.*?)",/',1)">$arr_all[1][1],1)">$arr1);从js块中匹配要的数据 $list = array_unique($arr1[1]);(可省)保证不重复 //以下则是同理,循环则可 for($i=0;$i<=6;$i=$i+2){ $detail_url = 'ht*****em/'.$list[$i]; $detail_res = curl_get_contents($detail_url); $detail_res,1)">$arr_detailpreg_match('/"desc"\:"(.*?)",1)">$arr_detail[1][1],1)">$arr_content); *** *** *** $ret=curl_post('http://**********cms.PHP',1)">$result);此脚本未放在服务器上,原因大家懂就好哈。 } function curl_get_contents($cookie='',1)">$referer='',1)">$timeout=300,1)">$ishead=0) { $curl = curl_init(); curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); curl_setopt($timeoutif($cookie) { curl_setopt( ); } $referer) { curl_setopt (); } $ssl = substr(TRUE : FALSE; if ($ssl) { curl_setopt(false); curl_setopt($res = curl_exec($curlreturn $res; curl_close(); } curl post数据到服务器 function curl_post($ch =$ch,1)">curl_setopt($ch,1); curl_setopt(true); $output = curl_exec($ch); curl_close($output; } ?>
5.fsockopen()函数 socket模式(没用过,以后可以试试)
socket 模式能否正确执行,也跟服务器的设置有关系,具体可以通过 PHPinfo 查看服务器开启了哪些通信协议
<?PHP $fp = fsockopen("t.qq.com",80,1)">$errno,1)">$errstr,30if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { $out = "GET / HTTP/1.1\r\n"; $out .= "Host: t.qq.com\r\n"$out .= "Connection: Close\r\n\r\n"fwrite($fp,1)">$outwhile (!feof()) { echo fgets(); }
6.snoopy插件(最新版本是Snoopy-1.2.4.zip Last Update: 2013-05-30,推荐大家使用)
使用网上非常流行的 snoopy 来进行采集,这是一个非常强大的采集插件,并且它的使用非常方便,你也可以在里面设置 agent 来模拟浏览器信息。
说明:设置 agent 是在 Snoopy.class.PHP 文件的第45行,请在该文件中搜索 “var 公式输入有误
_SERVER[‘HTTP_USER_AGENT’]; 可以得到浏览器信息,将 echo 出来的内容复制到 agent 里面就可以了。
<?引入snoopy的类文件 require('Snoopy.class.PHP'初始化snoopy类 $snoopy=new Snoopy; $url="[http://t.qq.com](http://t.qq.com/)"; 开始采集内容` $snoopy->fetch(保存采集内容到$lines_string $lines_string=$snoopy->results; 输出内容,嘿嘿,大家也可以保存在自己的服务器上 $lines_string;
更多学习内容可以访问从码农成为架构师的修炼之路