php file_get_contents 设置代理抓取页面示例
file_get_contents函数在php中可以直接打开本地文件也可以直接抓取远程服务器文件,如果简单的采集我们可以使用file_get_contents直接来操作,如果有防采集我们可能需要代理来操作,下面我来介绍file_get_contents抓取页面示例。
例1,普通页面获取
例如,访问54master论坛,想抓取首页里 所有h3标记内的元素。
<?php $url = 'http://www.phprm.com'; $contents = @file_get_contents($url); //preg_match_all("/<p class="right forumcount">(.*?)</p>/is",$contents,$content); preg_match_all("/<h3>(.*?)</h3>/is", $contents, $content); print_r($content[0]); ?>
例2,设置代码IP去采集数据
使用file_get_contents 和 stream_context_create 即可。
代码如下:
<?php $aContext = array( 'http' => array( 'proxy' => 'tcp://192.168.0.2:3128', //这里设置你要使用的代理ip及端口号 'request_fulluri' => true, ) , ); $cxContext = stream_context_create($aContext); $sFile = file_get_contents("http://www.phprm.com", False, $cxContext); echo $sFile; ?>
以上代码适用于正常情况,但是如果目标页面需要登录或需要认证信息才能访问的话,可以加多一句代码。
<?php $auth = base64_encode('LOGIN:PASSWORD'); //LOGIN:PASSWORD 这里是你的账户名及密码 $aContext = array( 'http' => array( 'proxy' => 'tcp://192.168.0.2:3128', //这里设置你要使用的代理ip及端口号 'request_fulluri' => true, 'header' => "Proxy-Authorization: Basic $auth", ) , ); $cxContext = stream_context_create($aContext); $sFile = file_get_contents('http://www.phprm.com', False, $cxContext); echo $sFile; ?>
这样就可以使用代理来抓取页面或文件了
教程网址:http://www.phprm.com/code/52273.html
欢迎收藏∩_∩但请保留本文链接。