在開發資訊聚合類網站時,經常需要從知名技術社區(如 CSDN)抓取最新文章。本文將詳細介紹如何使用 PHP 的 cURL 擴展結合正則表達式,實現對 CSDN 首頁新聞鏈接的批量採集,並進一步提取文章標題與正文內容,最後演示如何配合 ThinkPHP 框架入庫且自動去重。
https://*.csdn.net/a/xxxx/xxxx.html 格式的文章鏈接。<h1> 標題與 class="blkCont" 正文區塊。<?php
function csdn() {
$url = "https://www.csdn.net";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_ENCODING, 'utf8');
$content = curl_exec($ch);
// 提取文章鏈接
preg_match_all("/http\:\/\/\w*\.csdn\.net\/a\/\d*\/\d*\.html/", $content, $match);
$weburl = array_unique($match[0]);
$list = [];
$j = 0;
foreach ($weburl as $vo) {
curl_setopt($ch, CURLOPT_URL, $vo);
$detail = curl_exec($ch);
// 匹配標題與正文
preg_match_all("/\<h1\>(.*)\<\/h1\>|\<div\s*class\=\"blkCont.*([\s\S]*)\<div\s*class\=\"page\".*\>/", $detail, $m);
if (!empty($m[2][1])) {
$list[$j]['content'] = $m[2][1];
$list[$j]['title'] = $m[1][0];
$j++;
}
}
curl_close($ch);
print_r($list); // $list 即為採集到的新聞二維數組
}
?>
實際專案中需避免重複入庫。下方代碼展示如何在 ThinkPHP 3.x 環境下,利用 MD5 對標題指紋比對實現去重,並自動記錄分類、作者、時間等字段。
<?php
function csdn($uid) {
$url = "https://www.csdn.net";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_ENCODING, 'utf8');
$content = curl_exec($ch);
preg_match_all("/http\:\/\/\w*\.csdn\.net\/a\/\d*\/\d*\.html/", $content, $match);
$weburl = array_unique($match[0]);
$list = [];
$j = 0;
foreach ($weburl as $vo) {
curl_setopt($ch, CURLOPT_URL, $vo);
$detail = curl_exec($ch);
preg_match_all("/\<h1\>(.*)\<\/h1\>|\<div\s*class\=\"blkCont.*([\s\S]*)\<div\s*class\=\"page\".*\>/", $detail, $m);
if (!empty($m[2][1])) {
$list[$j]['content'] = $m[2][1];
$list[$j]['title'] = $m[1][0];
$j++;
}
}
curl_close($ch);
// ThinkPHP 操作
$db = M('news');
$news = $db->where("uid=" . $uid)->select();
foreach ($list as $vo) {
$flag = true;
foreach ($news as $value) {
if (md5($value['title']) == md5($vo['title'])) {
$flag = false;
break;
}
}
if ($flag) {
$vo['uid'] = $uid;
$vo['date'] = date('Y-j-m H:i:s');
$vo['author'] = Session::get("admin");
$vo['iscommand'] = 1;
$db->add($vo);
}
}
}
?>
CURLOPT_ENCODING 設置為 utf8,避免中文亂碼。usleep() 或使用隊列異步採集,防止被目標站封禁 IP。通過 cURL + 正則的組合,可快速實現對 CSDN 等技術站點的內容採集。配合框架的 ORM 與去重邏輯,即可構建穩定的資訊聚合入庫流程。實際部署時請遵守目標站 robots.txt 協議,並控制採集頻率,做負責任的開發者。