百度空间 | 百度首页 
 
查看文章
 
php采集程序
2008-04-15 19:12

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文章 | 添加到搜藏 | 浏览() | 评论 (3)
最近读者:
 
网友评论:
1
2008-06-22 23:23 | 回复
不错!!!
 
2
2009-01-14 15:55 | 回复
有错误的哦,地址不是这样写的吧,没有转义,你有没有测试过啊
 
3
2009-06-17 11:33 | 回复
echo $content[$i]; 要改成echo $content[1];
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     
 
精彩相册
   
     

©2009 Baidu