通過請求 site:domain.com 搜索頁,解析 #resultStats 區域提取收錄數字。注意:Google 反爬機制嚴格,生產環境建議使用官方 Search Console API 或第三方服務。
<?php
/**
* 獲取域名 Google 收錄量(僅供學習/低頻使用)
* @param string $domain 目標域名,如 example.com
* @return int|false 收錄數量,失敗返回 false
*/
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" .
"Accept-Language: zh-CN,zh;q=0.9,en;q=0.8\r\n",
'timeout' => 10,
'ignore_errors' => true,
],
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
]
];
$context = stream_context_create($opts);
$html = @file_get_contents($url, false, $context);
if ($html === false) return false;
// 解析 resultStats 區域,格式約為 "約 1,230,000 項結果"
if (preg_match('/id=["\']resultStats["\'][^>]*>(.*?)<\/div>/is', $html, $m)) {
$text = strip_tags($m[1]);
// 提取數字(去除逗號、中文約字等)
$numStr = preg_replace('/[^\d]/', '', $text);
return (int)$numStr;
}
return false;
}
// 使用示例
$count = getGoogleIndexCount('jb51.net');
if ($count !== false) {
echo "jb51.net Google 收錄約 {$count} 條\n";
} else {
echo "獲取失敗,可能被反爬或結構變更\n";
}
| 方案 | 優點 | 缺點 |
|---|---|---|
| Google Search Console API | 官方、準確、無反爬 | 需驗證站點擁有權、配額限制 |
| 第三方 SEO 工具 API | 數據豐富(關鍵詞、排名、反鏈) | 付費、依賴第三方 |
| 自建爬蟲池 + 代理 IP | 完全可控 | 維護成本高、法律風險 |
大規模抓取搜索引擎結果可能違反《計算機信息網絡國際聯網管理暫行規定》及 Google 服務條款。建議: