萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 獲取 Google 收錄量示例:站內搜尋 site: 語法爬取

原理說明

利用 Google 搜尋 site:domain.com 語法,解析回傳 HTML 中 #resultStats 區塊的數字,估算網站收錄頁面數。注意:頻繁請求可能觸發 Google 反爬蟲機制(驗證碼、IP 封鎖),生產環境建議使用官方 Search Console API。

實現代碼

<?php
function getGoogleIndexCount($domain) {
    $url = 'https://www.google.com/search?q=site:' . urlencode($domain);
    $opts = [
        'http' => [
            'method' => 'GET',
            'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n",
            'timeout' => 10,
        ]
    ];
    $context = stream_context_create($opts);
    $html = @file_get_contents($url, false, $context);
    if ($html === false) {
        return 'Request failed';
    }

    // 解析結果統計區塊,正則需隨 Google 頁面結構調整
    if (preg_match('/id=["\']resultStats["\'][^>]*>(.*?)<\/div>/is', $html, $matches)) {
        $text = strip_tags($matches[1]);
        // 提取數字(可能包含逗號、空格、中文「約」等)
        if (preg_match('/([\d,\.]+)/', $text, $numMatch)) {
            return (int)str_replace(',', '', $numMatch[1]);
        }
    }
    return 'Parse failed';
}

// 使用
echo 'example.com 收錄量: ' . getGoogleIndexCount('example.com');
?>

風險與替代方案

  • 反爬蟲風險:高頻請求會被要求驗證碼或封 IP。
  • HTML 結構變動:正則易失效,需持續維護。
  • 推薦方案:Google Search Console API(需驗證站長權限)、第三方 SEO 工具 API(Ahrefs, Semrush 等)。
copyright © 萬盛學電腦網 all rights reserved