首页 > php开发 > php file_get_contents 设置代理抓取页面示例

php file_get_contents 设置代理抓取页面示例

file_get_contents函数在php中可以直接打开本地文件也可以直接抓取远程服务器文件,如果简单的采集我们可以使用file_get_contents直接来操作,如果有防采集我们可能需要代理来操作,下面我来介绍file_get_contents抓取页面示例.

例1,普通页面获取

例如,访问54master论坛,想抓取首页里 所有h3标记内的元素,代码如下:

$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 即可,代码如下:

$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;

以上代码适用于正常情况,但是如果目标页面需要登录或需要认证信息才能访问的话,可以加多一句代码,代码如下:

$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/develop/fs3747.html

转载随意,但请附上文章地址:-)

标签:file_get_contents 抓取页面

相关文章

发表留言