[麦先生]使用正则做一个简单的数据采集

    网上有的朋友在去面试过程中有被要求去做数据采集工作的,但是由于对正则匹配运用的的不熟悉,而陷入了学而无以致用局面尴尬局面;做为新人我自己用所学过的知识尝试着做了一个网站详情页部分信息的数据采集,其中有逻辑不严谨或者应用不恰当的地方欢迎各位大神斧正;

    做数据采集的流程:

      进入一个网站后首先要查看网页源代码,审查检测源代码中是否存在我们需要的内容,如果有则可以直接使用正则匹配的方式来进行数据的抓取和提取;

      假如我们需要的内容是由网站的js动态生成的,我们就不能直接对网站进行正则匹配的方式进行数据抓取,这时我们需要打开(注:我用的火狐)Firebug网络中查看服务器传输回的数据里可以找到服务器返回的源码,反而更加便捷;

      在PHP中有一些内置的函数可以帮助我们更快捷的抓取网页源代码比如:file_get_contents; 包括正则匹配里常用的preg_match,preg_match_all;正确并熟练的使用PHP内置函数和方法可以极大节省我们的时间;

      

class PHP1
{
/**
* 采集详情页
*/
public function getDetailPage($url)
{
//获取源代码
$str = Curl::get($url);

//提取标题内容
preg_match('/<h1>(.*)</h1>.*发布日期:(.*)&nbsp 来源.*<div class="article_review">(.*)</div>.*<div class="article_content">.*转载请注明来源.*<a.*>.*</a>(.*)转载请注明来源.*</div>/isU', $str, $temp);

//创建pdo对象
$pdo = new PDO('mysql:host=localhost;dbname=lamp;charset=utf8;port=3306','root','');

//发送预处理指令
$stmt = $pdo->prepare('insert into article (title, con, intro, time)values(:title, :con, :intro, :time)');

//参数的绑定
$arr = array(
':title'=>$temp[1],
':con'=>$temp[4],
':intro'=>$temp[3],
':time'=>$temp[2]
);
$stmt->execute($arr);

$id = $pdo->lastInsertId();

return $id;
}

/**
* 采集列表页 获取详情页的url
*/
public function getListUrl($url)
{
//获取当前列表页中的源代码
$data = Curl::get($url);

if(empty($data)){
return false;
}
//正则匹配
preg_match_all('/<li>.*<div class="NewTitle">.*<h2><a.*href="(.*)".*></li>/isU', $data, $temp);
//返回结果
return $temp[1];
}

/**
* 开始采集
*/
public function startCollect(){
$urls = $this->getListUrl('http://www.php1.cn/category/44.html');
//遍历
foreach ($urls as $key => $value) {
$this->getDetailPage($value);
}
}
}

/**
* curl工具类
*/
class Curl{
public static function get($url){
//初始化curl资源
$ch = curl_init($url);
//设置请求选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//发送请求
$res = curl_exec($ch);
//
return $res;
}
}

// $res = get('http://www.php1.cn/Content/XiaoXinGaoXiaoLvDe_sql_ChaXunTaYeHuiDaoZhiWangZhanXiangYingBianMan.html');

//创建对象
// $obj = new PHP1;

// $url = 'http://www.php1.cn/Content/XiaoXinGaoXiaoLvDe_sql_ChaXunTaYeHuiDaoZhiWangZhanXiangYingBianMan.html';
// $res = $obj->getDetailPage($url);

//读取列表页的内容
// $obj->getListUrl('http://www.php1.cn/category/44.html');

// $obj -> startCollect();

//如果代码报错 curl_init undefined
//wampserver->php->php extensions->php_curl

      

原文地址:https://www.cnblogs.com/maixiansheng/p/5450298.html