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

PHP 串接百度 API:關鍵字相關搜尋與原創度檢測

     編輯:PHP 相關知識

功能概覽

提供兩項核心功能:抓取百度相關搜尋建議、計算內容原創度指標。適用於 SEO 優化、內容採集系統、關鍵字擴展等場景。

核心類別實作

<?php
class BaiduSeo {
    /**
     * 建構搜尋請求 URI
     * @param string $words 關鍵字
     * @return string 完整查詢字串
     */
    public static function buildRequestUri($words) {
        $words = urlencode(Text::convertEncoding($words, 'GBK', 'UTF-8'));
        return '/s?wd=' . $words;
    }

    /**
     * 取得相關搜尋關鍵字
     * @param string $words 查詢關鍵字
     * @return array|false 相關搜尋陣列或失敗
     */
    public static function getRelateSearch($words) {
        $content = self::getContent($words);
        
        // 解析相關搜尋區塊
        if (preg_match('/<div id="rs">(((?!<\/div>).)*)<\/div>/s', $content, $result)) {
            if (preg_match_all('/<a((?!>).)*>(.*?)<\/a>/s', $result[1], $matches)) {
                return $matches[2];
            }
        }
        return false;
    }

    /**
     * 計算原創度指標(em 標籤出現次數)
     * 數值越高表示文字長度越長且越不原創
     * @param string $words 以空格分隔的關鍵字
     * @return int 原創度分數
     */
    public static function getEmTimes($words) {
        $wordList = explode(' ', $words);
        $content = self::getContent($words);
        
        // 擷取所有 <em> 標籤內容
        preg_match_all('/<em>(((?!<\/em>).)*)<\/em>/s', $content, $result);
        
        if (!isset($result[1]) || count($result[1]) === 0) {
            return 0;
        }
        
        $wordTable = array_count_values($result[1]);
        $times = 0;
        
        foreach ($wordList as $piece) {
            if (array_key_exists($piece, $wordTable)) {
                $times += $wordTable[$piece];
            }
        }
        return $times;
    }

    /**
     * 取得搜尋頁面內容(含快取機制)
     * @param string $words 關鍵字
     * @return string HTML 內容
     */
    public static function getContent($words) {
        static $loadedContents = [];
        
        if (!isset($loadedContents[$words])) {
            $url = 'https://www.baidu.com' . self::buildRequestUri($words);
            $content = file_get_contents($url);
            $content = Text::convertEncoding($content, 'UTF-8', 'GBK');
            $loadedContents[$words] = $content;
        }
        return $loadedContents[$words];
    }

    /**
     * 檢查是否觸發百度驗證碼
     * @param string $content 頁面內容
     * @return void
     */
    public static function checkVerify($content) {
        if (strpos($content, 'https://verify.baidu.com/') !== false) {
            // 觸發驗證,需處理異常情況
            throw new Exception('百度要求驗證碼,請降低請求頻率或使用代理');
        }
    }
}

使用範例

<?php
require_once 'BaiduSeo.php';

$keywords = 'PHP 框架 推薦';

try {
    // 取得相關搜尋
    $related = BaiduSeo::getRelateSearch($keywords);
    echo "相關搜尋:\n";
    print_r($related);

    // 計算原創度
    $emTimes = BaiduSeo::getEmTimes($keywords);
    echo "原創度指標 (em_times):$emTimes\n";
    
    // 指標解讀
    if ($emTimes > 50) {
        echo "⚠️ 內容可能重複度較高,建議重寫\n";
    } elseif ($emTimes > 20) {
        echo "⚡ 內容有一定重複,可適度修改\n";
    } else {
        echo "✅ 內容原創度較好\n";
    }
} catch (Exception $e) {
    echo "錯誤:" . $e->getMessage();
}

技術細節與注意事項

編碼轉換

百度搜尋頁面使用 GBK 編碼,PHP 內部建議統一 UTF-8,需雙向轉換。`Text::convertEncoding()` 為自訂工具類,可用 `mb_convert_encoding()` 或 `iconv()` 替代。

快取機制

靜態變數 `$loadedContents` 避免同一關鍵字重複請求,減少頻寬與被封風險。

反爬蟲應對

  • 請求間隔隨機延遲(1-3 秒)
  • 使用代理 IP 池輪換
  • 模擬真實瀏覽器 User-Agent
  • 處理驗證碼頁面(需人工或打碼平台介入)
  • 遵守 robots.txt 與搜尋引擎服務條款

法律與道德提醒

大量抓取搜尋引擎資料可能違反服務條款。建議:

  • 使用官方 API(百度站長平台、關鍵字規劃師)
  • 控制抓取頻率,避免影響服務
  • 僅供內部分析,勿重新發布搜尋結果

現代替代方案

  • 百度站長平台 API:官方提供關鍵字工具、收錄查詢
  • 第三方 SEO 工具:Ahrefs、SEMrush、5118 等付費服務
  • 自建搜尋引擎:Elasticsearch + 爬蟲建立專屬索引
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved