分析蜘蛛爬取行為是 SEO 優化關鍵。本文實現一個輕量級蜘蛛識別器:解析 User-Agent、匹配已知蜘蛛特徵、記錄訪問日誌到文件,可直接集成到項目公共入口。
'googlebot',
'Baidu' => 'baiduspider',
'Bing' => 'bingbot',
'Yahoo' => 'slurp',
'Sogou' => 'sogou spider',
'Soso' => 'sosospider',
'360' => '360spider',
'Shenma' => 'yodaobot', // 神馬搜索
'ByteDance' => 'bytespider', // 字節跳動
'Yandex' => 'yandexbot',
'DuckDuckGo' => 'duckduckbot',
];
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
if (empty($userAgent)) return; // 無 UA 可能是採集器或測試工具
// 2. 匹配蜘蛛
$spiderName = false;
foreach ($bots as $name => $signature) {
if (strpos($userAgent, $signature) !== false) {
$spiderName = $name;
break;
}
}
if (!$spiderName) return; // 非已知蜘蛛,不記錄
// 3. 記錄日誌
$logFile = __DIR__ . '/logs/spider_' . date('Y-m') . '.log'; // 按月分文件
$logDir = dirname($logFile);
if (!is_dir($logDir)) mkdir($logDir, 0755, true);
$time = date('Y-m-d H:i:s');
$url = $_SERVER['REQUEST_URI'] ?? '';
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$logLine = sprintf(
"[%s] Spider: %-12s IP: %-15s URL: %s UA: %s\n",
$time, $spiderName, $ip, $url, $userAgent
);
// 追加寫入(FILE_APPEND + LOCK_EX 防併發亂序)
file_put_contents($logFile, $logLine, FILE_APPEND | LOCK_EX);
}
// 使用:在 index.php 或框架入口最早處調用
logSpiderVisit();
[2024-01-15 10:30:45] Spider: Baidu IP: 180.76.15.12 URL: /article/123 UA: mozilla/5.0 (compatible; baiduspider/2.0; +https://www.baidu.com/search/spider.html) [2024-01-15 10:31:02] Spider: Google IP: 66.249.64.12 URL: /sitemap.xml UA: mozilla/5.0 (compatible; googlebot/2.1; +https://www.google.com/bot.html)
惡意採集器常偽造 User-Agent。真實蜘蛛 IP 可通過反向 DNS 驗證:
function isRealSpider($spiderName, $ip) {
$host = gethostbyaddr($ip);
$patterns = [
'Google' => '/\.googlebot\.com$/',
'Baidu' => '/\.baidu\.com$/',
'Bing' => '/\.search\.msn\.com$/',
'Sogou' => '/\.sogou\.com$/',
'360' => '/\.360\.cn$/',
'ByteDance' => '/\.bytedance\.com$/',
];
if (!isset($patterns[$spiderName])) return true; // 無驗證規則默認信任
return (bool)preg_match($patterns[$spiderName], $host);
}
// 在 logSpiderVisit 中調用
if ($spiderName && !isRealSpider($spiderName, $ip)) {
$spiderName = 'Fake-' . $spiderName; // 標記為疑似偽造
}
# 統計各蜘蛛今日爬取量
grep "$(date +%Y-%m-%d)" logs/spider_$(date +%Y-%m).log | awk '{print $3}' | sort | uniq -c | sort -rn
# 統計 Baidu 爬取的 URL TOP 20
grep "Baidu" logs/spider_$(date +%Y-%m).log | awk '{print $6}' | sort | uniq -c | sort -rn | head -20
# 發現 404 頁面被爬取
grep " 404 " logs/spider_$(date +%Y-%m).log | awk '{print $6}' | sort | uniq -c | sort -rn
輕量級蜘蛛日誌記錄器幫你掌握「誰來了、爬了什麼、何時爬」。結合反向 DNS 驗證過濾偽造 UA,定期分析日誌發現 404、抓取頻次、新頁面收錄情況,指導 SEO 優化策略。