php教程|php手册
php,正则,匹配,获取,指定,url,网页,页面,超级链接,地址,在,数据采集,与,页面,分析,中,常需要,常,需要,
php教程-php手册
在数据采集与页面分析中,常需要抓取给定url页面的内容,或者第B、第三层次深度页面内容。
云牛品论坛源码,vscode git 替换,ubuntu achi,tomcat登入,安卓sqlite传图像,discuz插件语言,开发网页前端框架下载,蓝桥杯是不是反爬虫,php json 接口,昆明seo培训招生,百度竞价网站源码,在线网页聊天室聊天页面asp,织梦模板风格 常量lzw
这里是一个测试例子的实现,仅供参考。
马士兵 坦克大战 源码,ubuntu 打开大文档,图片爬虫蓝鲸阅读,piegraph php,seo外贸价格lzw
代码如下:
asp树形分类源码,磊科支持ubuntu,tomcat7过滤特殊字符,爬虫包维护,php数据库返回json,吉林seo服务lzw
/*
匹配给定页面链接
return:array match[link,content,all]
*/
function match_links($host, $document) {
$pattern = ‘/(.*?)/i’;
preg_match_all($pattern, $document, $m);
return $m;
preg_match_all(“‘]+))[^>]*>?(.*?)’isx”,$document,$links);
while(list($key,$val) = each($links[2])) {
if(!empty($val))
if(preg_match(“/http/”,$val)){
$match[‘link’][] = $val;
}
else {
$match[‘link’][] = $host . $val;
}
}
while(list($key,$val) = each($links[3])) {
if(!empty($val))
if(preg_match(“/http/”,$val)){
$match[‘link’][] = $val;
}
else {
$match[‘link’][] = $host . $val;
}
}
while(list($key,$val) = each($links[4])) {
if(!empty($val))
$match[‘content’][] = $val;
}
while(list($key,$val) = each($links[0])) {
if(!empty($val))
$match[‘all’][] = $val;
}
return $match[‘link’];
}
/*
从给定url中获取页面文本内容
*/
function get_content_from_url($url) {
$str = @file_get_contents($url);
if(mb_check_encoding($str, “GBK”))
$str = iconv(“GBK”,”UTF-8″, $str);
$str = strip_tags($str); // 过滤html标签
/*
$str = preg_replace( “@<script(.*?)@is”, “”, $str );
$str = preg_replace( “@<iframe(.*?)@is”, “”, $str );
$str = preg_replace( “@<style(.*?)
@is”, “”, $str );
$str = preg_replace( “@@is”, “”, $str );
*/
//过滤非汉字字符
preg_match_all(‘/[x{4e00}-x{9fff}]+/u’, $str, $matches);
$str = join(‘,’, $matches[0]);
if(!$str)
return NULL;
return $str;
}
function get_content($url,$depth) {
if(!$url || $depth < 1)
return false;
while($depth > 1){
$str = @file_get_contents($url);
if(!$str)
return false;
$parseurl = parse_url($url);
if($parseurl[‘host’])
$host = $parseurl[scheme] . “://” . $parseurl[‘host’];
$arrlink = match_links($host,$str);
$arr_url = array_unique($arrlink);
$depth–;
foreach($arr_url as $url){
$content .= get_content($url, $depth); //递归调用
}
}
$content .= get_content_from_url($url);
return $content;
}