首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

使用 PHP 爬取 CSDN 首頁新聞實戰教學

     編輯:PHP 相關知識

前言

在開發資訊聚合類網站時,經常需要從知名技術社區(如 CSDN)抓取最新文章。本文將詳細介紹如何使用 PHP 的 cURL 擴展結合正則表達式,實現對 CSDN 首頁新聞鏈接的批量採集,並進一步提取文章標題與正文內容,最後演示如何配合 ThinkPHP 框架入庫且自動去重。

核心思路

  1. 請求 CSDN 首頁,獲取 HTML 原始碼。
  2. 使用正則提取符合 https://*.csdn.net/a/xxxx/xxxx.html 格式的文章鏈接。
  3. 去重後遍歷每個鏈接,再次請求詳情頁。
  4. 從詳情頁中用正則匹配 <h1> 標題與 class="blkCont" 正文區塊。
  5. 將結果組裝為二維數組,後續可直接寫入資料庫。

基礎版實現代碼

<?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 整合與去重入庫

實際專案中需避免重複入庫。下方代碼展示如何在 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);
        }
    }
}
?>

關鍵點提醒

  • 正則維護:CSDN 頁面結構若變更,需同步更新正則模式。
  • 編碼處理:確保 CURLOPT_ENCODING 設置為 utf8,避免中文亂碼。
  • 請求頻率:建議在循環中加入 usleep() 或使用隊列異步採集,防止被目標站封禁 IP。
  • 去重策略:除 MD5 外,亦可使用 URL 唯一索引或標題+來源聯合索引提高可靠性。

總結

通過 cURL + 正則的組合,可快速實現對 CSDN 等技術站點的內容採集。配合框架的 ORM 與去重邏輯,即可構建穩定的資訊聚合入庫流程。實際部署時請遵守目標站 robots.txt 協議,並控制採集頻率,做負責任的開發者。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved