前一段时间我师父让写一个文章采集器,嘻嘻,很显然我写的不是特别好,这是他写的我就借鉴一下,哇咔咔
创建一个采集类
<?php
header("content-type:text/html; charset=gb2312");
class Collect
{
var $html;
function __construct($cjurl)
{
$ch = curl_init();
$this_header = array("content-type: application/x-www-form-urlencoded;charset=gb2312");
$timeout = 10;
curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
curl_setopt ($ch,CURLOPT_URL,$cjurl);
curl_setopt ($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
if($filehtml= curl_exec($ch))
{
$this->html=$filehtml;
}
curl_close($ch);
if($this->html)
{
$info=array();
preg_match('/<div id="article">(.*)<span class="STYLE1">/s',$this->html,$info);
$this->html=$info[0];
}
}
//获取标题
function findtitle()
{
$title=array();
preg_match('/<h1>(.*)<\/h1>/s',$this->html,$title);
return $title[0];
}
//获取内容
function findcontent()
{
$html=$this->html;
$content=array();
preg_match('/<div id="article_body">(.*)/s',$this->html,$content);
return $content[0];
}
}
?>
用正则表达式提取的内容,标题,等信息
<?php
include "collection.php";
//获取一篇文章
//$cj = new Collect("http://www.hack86.com/hkjs/rumen/437.html");
//echo $cj->findtitle();
//echo $cj->findcontent();
//连接数据库
$conn=mysql_connect("localhost","root","root");
mysql_select_db("qyxs",$conn);
mysql_set_charset('gb2312',$conn);
mysql_query("set names gb2312");
function showhtml($cjurl)
{
$cj=new Collect($cjurl);
$title=$cj->findtitle();
$content=$cj->findcontent();
if($title!=""&&$content!="")
{
$uuid=uniqid();
$sql="insert into `qyxs_news` (title,content) values ('$title','$content')";
mysql_query($sql);
}
}
for($i=421;$i<438;$i++)
{
$url="http://www.hack86.com/hkjs/rumen/".$i.".html";
showhtml($url);
sleep(2);
}
mysql_close($conn);
?>
我根据我本地的数据库采集出来的内容是