set_charset('UTF8'); # 设置数据库编码
function data($url) {
global $mysqli;
$result = file_get_contents($url); # $result 获取 url 链接内容(注意:这里是文章列表链接)
$pattern = '/
/Usi'; # 取得文章 url 的匹配正则
preg_match_all($pattern,$result,$arr); # 把文章列表 url 分配给数组$arr(二维数组)
foreach ($arr[1] as $val) {
$val = 'http://www.hqew.com' . $val; # 真实文章 url 地址
$re = file_get_contents($val); # $re 为文章 url 的内容
$pa = '/
(.+)s+
.+
s+
/Usi'; # 取得文章内容的正则
preg_match_all($pa,$re,$array); # 把取到的内容分配到数组 $array
$content = trim($array[5][0]);
$con = array(
'title'=>mysqlString($array[1][0]),'date'=>mysqlString($array[2][0]),'author'=>mysqlString(stripAuthorTag($array[3][0])),'source'=>mysqlString($array[4][0]),'content'=>mysqlString(stripContentTag($content))
);
$sql = "INSERT INTO article(title,date,author,source,content) VALUES ('{$con['title']}','{$con['date']}','{$con['author']}','{$con['source']}','{$con['content']}')";
$row = $mysqli->query($sql); # 添加到数据库
if ($row) {
echo 'add success!';
} else {
echo 'add failed!';
}
}
}
/**
* stripOfficeTag($v) 对文章内容进行过滤,比如:去掉文章中的链接,过滤掉没用的 HTML 标签……
* @param string $v
* @return string
*/
function stripContentTag($v){
$v = str_replace('
','',$v);
$v = str_replace('
',$v);
$v = preg_replace('/(.+)/Usi','1',$v);
$v = preg_replace('%(
]*>(.*))%Usi','2',$v);
$v = preg_replace('%(s+class="Mso[^"]+")%si',$v);
$v = preg_replace('%( style="[^"]*mso[^>]*)%si',$v);
$v = preg_replace('//',$v);
return $v;
}
/**
- stripTitleTag($title) 对文章标题进行过滤
- @param string $v
- @return string
*/
function stripAuthorTag($v) {
$v = preg_replace('/<a href=".+" target="_blank">(.+)</a>/Usi',$v);
return $v;
}
/**
- mysqlString($str) 过滤数据
- @param string $str
- @return string
*/
function mysqlString($str) {
return addslashes(trim($str));
}
/**
- init($min,$max) 入口程序方法,从 $min 页开始取,到 $max 页结束
- @param int $min 从 1 开始
- @param int $max
- @return string 返回 URL 地址
*/
function init($min=1,$max) {
for ($i=$min; $i<=$max; $i++) {
data("http://www.hqew.com/info-c10-{$i}.html");
}
}
init(1,500); // 程序入口,从第一页开始抓,抓取500页
?>
入口方法 init($min,$max) 如果想抓取 1-500 页面内容,那么 init(1,500) 即可!这样,用不了多长时间,华强电子网的资讯就会全部抓取到数据库里面了。^_^