php采集程序

其实,采集程序最简单的思路就是:获取页面代码——分析代码——获取需要的部分——写入数据库

对于采集程序来说,使用PHP来写的话,其实不算太好的,因为PHP并不支持多线程,对于采集来说,若没有多线程,将会是非常痛苦的一件事

不过可以使用frame等来设置同时几个页面一起采集,这样就能增加速度了,在这里我不讨论怎么多线程,我只说怎么用PHP来进行简单的采集

先确定采集目标:http://cn.jokes.yahoo.com/jok/index.html

这是雅虎的笑话栏目,我就以这个来进行讲解吧

首先分析一下网页,可以知道连接形式为:<img src="http://cn.yimg.com/i/cn/px_ar.gif" width=5 height=12 border=0 hspace=5><a href="http://cn.jokes.yahoo.com/07-07-/55/27lot.html" class=list target=_blank><big>头发与智慧</big></a>

使用正则表达式将它表示出来为:/hspace=5><a href="http://cn.jokes.yahoo.com/(.*).html" class=list target=_blank>/isU

书写PHP代码:

代码
// 采集首页地址 
$url="<a href=\"http://cn.jokes.yahoo.com/jok/index.html\">http://cn.jokes.yahoo.com/jok/index.html</a>"; 
// 获取页面代码 
$r = file_get_contents($url); 
// 设置匹配正则 
$preg = '/hspace=5><a href="http://cn.jokes.yahoo.com/(.*).html" class=list target=_blank>/isU'; 
// 进行正则搜索 
preg_match_all($preg, $r, $title); 


通过上面的代码,$title[1][num]就是连接的地址了,接着分析内容页,得到内容匹配正则为:/<div id="newscontent">(.*)</div>/isU

继续写代码:

代码
// 计算标题数量 
$count = count($title[1]); 
// 通过标题数量进行内容采集 
for($i=0;$i<$count;$i++) { 
   // 设置内容页地址 
   $jurl = "<a href=\"http://cn.jokes.yahoo.com/\">http://cn.jokes.yahoo.com/</a>" . $title[1][$i] . ".html";
   // 获取内容页代码 
   $c = file_get_contents($jurl); 
   // 设置内容页匹配正则 
   $p = '/<div id="newscontent">(.*)</div>/isU'; 
   // 进行正则匹配搜索 
   preg_match($p, $c, $content); 
   // 输出标题 
   echo $title[1][$i] . "
"; 
   // 输出内容 
   echo $content[$i]; 
}



这样,一个简单的采集工具就写出来了,其他的功能只需要再进一步的完善就可以了

完整代码:

代码
<?php 
// 采集首页地址 
$url = "<a href=\"http://cn.jokes.yahoo.com/jok/index.html\">http://cn.jokes.yahoo.com/jok/index.html</a>"; 
// 获取页面代码 
$r = file_get_contents($url); 
// 设置匹配正则 
$preg = '/hspace=5><a href="http://cn.jokes.yahoo.com/(.*).html" class=list target=_blank>/isU'; 
// 进行正则搜索 
preg_match_all($preg, $r, $title); 
// 计算标题数量 
$count = count($title[1]); 
// 通过标题数量进行内容采集 
for($i=0;$i<$count;$i++) { 
   // 设置内容页地址 
   $jurl = "<a href=\"http://cn.jokes.yahoo.com/\">http://cn.jokes.yahoo.com/</a>" . $title[1][$i] . ".html"; 
   // 获取内容页代码 
   $c = file_get_contents($jurl); 
   // 设置内容页匹配正则 
   $p = '/<div id="newscontent">(.*)</div>/isU'; 
   // 进行正则匹配搜索 
   preg_match($p, $c, $content); 
   // 输出标题 
   echo $title[1][$i] . "
"; 
   // 输出内容 
   echo $content[$i]; 

?>

你可能感兴趣的:(php采集)