智能文章系统实战-数据采集(3)
admin 发布于:2018-6-19 18:26 有 3159 人浏览,获得评论 0 条 标签: php
<?php
require_once('./inc.php');
//利用正则分析获取页面内容中相关的标题和内容。完成数据采集。
//采集的页数
$p=1;
//循环采集
for($i=1;$i<=$p;$i++)
{
//采集的列表地址(此地址仅供演示学习用)
$url='http://feed.mix.sina.com.cn/api/roll/get?pageid=153&lid=2509&k=&num=50&page='.$i;
//获取内容
$fileContent=file_get_contents($url);
//解析JSON
$jsonArray=json_decode($fileContent,true);
//获取列表数据
$dataList=$jsonArray['result']['data'];
if($dataList)
{
foreach($dataList as $key => $row)
{
$wapurl=$row['wapurl'];
//获取页面的HTML源码
$content=file_get_contents($wapurl);
//获取标题
preg_match('|<h1 class="art_tit_h1">(.*)</h1>|Uis',$content,$match);
$title=$match[1];
//获取类别
preg_match('|<h2 class="hd_tit_l">(.*)</h2>|Uis',$content,$match);
$category=preg_replace('/(\s+)/',' ',trim(strip_tags($match[1])));
//获取内容
preg_match('|<!--标题_e-->(.*)<div id=\'wx_pic\' style=\'margin:0 auto;display:none;\'>|Uis',$content,$match);
//过滤内容中多余的标签
$content=trim($match[1]);
$content=preg_replace("|<section(.*)</section>|Uis","",$content);
$content=preg_replace('|<h2 class="art_img_tit">(.*)</h2>|Uis',"",$content);
//过滤内容中多余的图片
preg_match_all('|<img (.*) src="(.*)" data-src="(.*)" (.*)>|Uis',$content,$imgMatch);
if($imgMatch[0])
{
foreach($imgMatch[0] as $imgKey => $img)
{
if(strpos($imgMatch[4][$imgKey],'style="display:none"')==true)
{
$content=str_replace($img,"",$content);
}
else
{
$content=str_replace($img,"<img src='".$imgMatch[3][$imgKey]."' ".$imgMatch[4][$imgKey]."/>",$content);
}
}
}
//把符合条件的数据存入数据库,完成数据采集
$times=time();
if($title && $content && strlen($title)>3 && strlen($content)>100)
{
//插入数据库
$sql="INSERT INTO article SET `title`='".addslashesObj($title)."',`content`='".htmlspecialcharsObj(addslashesObj($content))."',`times`='".$times."'";
$ret=$db->query($sql);
}
}
}
}
?>
总结:采用PHP正则分析网页源代码获取相关内容,把解析的内容插入数据库中。
