萬盛學電腦網

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

PHP 模擬搜尋引擎蜘蛛抓取與 SEO 分析:Title、Meta、Body 完整提取

核心功能

模擬百度/Google 蜘蛛 UA 抓取目標頁面,解析關鍵 SEO 元素:<title>、<meta keywords>、<meta description>、<body> 內容,快速診斷頁面 SEO 狀態。

完整實作程式碼

<?php
header("Content-Type: text/html; charset=utf-8");

function fetchPage($url) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; Baiduspider/2.0; +https://www.baidu.com/search/spider.html)',
        CURLOPT_HTTPHEADER     => [
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language: zh-CN,zh;q=0.9',
        ],
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $content = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200 || !$content) return false;
    return $content;
}

function analyzeSEO($html) {
    $dom = new DOMDocument();
    @$dom->loadHTML('' . $html); // 修正編碼
    $xpath = new DOMXPath($dom);
    
    // Title
    $titleNode = $xpath->query('//title')->item(0);
    $title = $titleNode ? trim($titleNode->textContent) : '無標題';
    
    // Meta Keywords & Description
    $keywords = $description = '';
    $metas = $xpath->query('//meta');
    foreach ($metas as $meta) {
        $name = strtolower($meta->getAttribute('name'));
        $property = strtolower($meta->getAttribute('property'));
        $content = $meta->getAttribute('content');
        
        if ($name === 'keywords' || $property === 'keywords') {
            $keywords = $content;
        }
        if ($name === 'description' || $property === 'og:description') {
            $description = $content;
        }
    }
    
    // Body 文字內容 (去除 script/style)
    $bodyNode = $xpath->query('//body')->item(0);
    $bodyText = '';
    if ($bodyNode) {
        // 移除 script/style
        $scripts = $xpath->query('.//script | .//style', $bodyNode);
        foreach ($scripts as $s) $s->parentNode->removeChild($s);
        $bodyText = trim(preg_replace('/\s+/', ' ', $bodyNode->textContent));
        $bodyText = mb_substr($bodyText, 0, 500); // 限制長度
    }
    
    return compact('title', 'keywords', 'description', 'bodyText');
}

// 主程式
$url = $_POST['url'] ?? 'https://example.com';
$html = fetchPage($url);
if ($html) {
    $seo = analyzeSEO($html);
    echo "<h3>SEO 分析結果</h3>";
    echo "<p><strong>Title:</strong> " . htmlspecialchars($seo['title']) . "</p>";
    echo "<p><strong>Keywords:</strong> " . htmlspecialchars($seo['keywords']) . "</p>";
    echo "<p><strong>Description:</strong> " . htmlspecialchars($seo['description']) . "</p>";
    echo "<p><strong>Body (前500字):</strong> " . htmlspecialchars($seo['bodyText']) . "</p>";
} else {
    echo "<p style='color:red'>抓取失敗,請檢查 URL 或網路</p>";
}

關鍵改良點 (對比原始碼)

原始碼問題改良方案
正則解析 HTML (脆弱)DOMDocument + XPath (標準、健壯)
User-Agent 固定舊版 IE可切換 Baiduspider/Googlebot/Chrome UA
無 HTTPS 支援cURL 自動處理 SSL
編碼硬編碼 GBKUTF-8 為主,自動偵測
無錯誤處理HTTP 狀態碼檢查、超時控制
直接輸出未轉義htmlspecialchars 防 XSS

進階 SEO 檢查項目

  • H1~H6 標題結構
  • 圖片 Alt 屬性
  • Canonical 標籤
  • Open Graph / Twitter Card
  • 結構化資料
  • 頁面載入速度 (需配合 Lighthouse/PageSpeed)
  • 行動版友善度

部署建議

  1. 做成 CLI 工具:php seo_check.php https://example.com
  2. 批次檢查 Sitemap 中所有 URL
  3. 整合到 CI/CD:部署前自動檢查關鍵頁面 SEO
  4. 定時排程監控競對頁面變化
copyright © 萬盛學電腦網 all rights reserved