萬盛學電腦網

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

PHP 使用 DOMDocument 解析網頁提取所有連結完整教學

為什麼選擇 DOMDocument?

相比正則表達式,DOMDocument 提供語義級的 HTML 解析,正確處理巢狀標籤、屬性順序、編碼、實體字元等邊界情況,是提取連結的標準做法。

基本提取範例

<?php
/**
 * 從指定 URL 提取所有連結
 * @param string $url 目標網址
 * @return array 連結陣列 ['url' => '...', 'text' => '...', 'title' => '...']
 */
function extractLinks($url) {
    $html = @file_get_contents($url);
    if ($html === false) {
        throw new RuntimeException("無法取得網頁內容: $url");
    }
    
    $dom = new DOMDocument();
    // 抑制 HTML5 標籤/屬性警告
    libxml_use_internal_errors(true);
    // 載入 HTML,指定編碼避免亂碼
    $dom->loadHTML('<meta charset="utf-8">' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();
    
    $links = [];
    $anchors = $dom->getElementsByTagName('a');
    
    foreach ($anchors as $a) {
        $href = $a->getAttribute('href');
        if (empty($href)) continue;
        
        // 轉換相對網址為絕對網址
        $absolute_url = resolveUrl($url, $href);
        
        $links[] = [
            'url'   => $absolute_url,
            'text'  => trim($a->textContent),
            'title' => $a->getAttribute('title') ?: '',
            'rel'   => $a->getAttribute('rel') ?: '',
            'target'=> $a->getAttribute('target') ?: '',
        ];
    }
    
    return $links;
}

/** 相對網址轉絕對網址 */
function resolveUrl($base, $relative) {
    // 已是絕對網址
    if (parse_url($relative, PHP_URL_SCHEME)) return $relative;
    
    $base_parts = parse_url($base);
    $base_path = rtrim(dirname($base_parts['path']), '/') . '/';
    
    if ($relative[0] === '/') {
        // 根相對路徑
        return $base_parts['scheme'] . '://' . $base_parts['host'] . $relative;
    } else {
        // 相對路徑
        return $base_parts['scheme'] . '://' . $base_parts['host'] . $base_path . $relative;
    }
}

// 使用範例
try {
    $links = extractLinks('https://example.com');
    foreach ($links as $link) {
        printf("[%s] %s (%s)\n", $link['url'], $link['text'], $link['title']);
    }
} catch (Exception $e) {
    echo "錯誤: " . $e->getMessage();
}

進階:使用 DOMXPath 精準查詢

<?php
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();

$xpath = new DOMXPath($dom);

// 1. 只取文章區塊內的連結
$article_links = $xpath->query('//article//a[@href]');

// 2. 排除特定類別 (如導航、頁尾)
$content_links = $xpath->query('//a[@href and not(ancestor::nav) and not(ancestor::footer)]');

// 3. 只取特定域名的外部連結
$external = $xpath->query('//a[@href and starts-with(@href, "http") and not(contains(@href, "example.com"))]');

// 4. 取得圖片連結
$images = $xpath->query('//img[@src]');
foreach ($images as $img) {
    echo $img->getAttribute('src') . "\n";
}

// 5. 結合屬性條件
$downloads = $xpath->query('//a[@href and contains(@href, ".pdf") or contains(@href, ".zip")]');

處理 JavaScript 動態渲染頁面

file_get_contents / DOMDocument 只能取得初始 HTML,無法執行 JavaScript。針對 SPA (Vue/React/Angular) 或 AJAX 載入內容:

方案 A:使用 Headless Chrome (推薦)

// 需安裝 chrome-php/chrome 或 spatie/browsershot
use HeadlessChromium\BrowserFactory;

$browser = BrowserFactory::create()->createBrowser();
$page = $browser->createPage();
$page->navigate('https://spa-example.com')->waitForNavigation();
$html = $page->getHtml();
// 再用 DOMDocument 解析 $html
$browser->close();

方案 B:分析 API 請求 (最佳效能)

// 開啟瀏覽器開發者工具 Network 面板
// 找出載入資料的 API 端點 (通常是 JSON)
// 直接用 PHP 請求 API
$api_url = 'https://api.example.com/articles?page=1';
$json = file_get_contents($api_url);
$data = json_decode($json, true);
// 直接處理結構化資料,無需解析 HTML

編碼問題完整解決方案

function fetchHtml($url) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Link Extractor/1.0)',
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_ENCODING => 'gzip, deflate', // 自動解壓
    ]);
    $html = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    
    if ($info['http_code'] !== 200) {
        throw new RuntimeException("HTTP {$info['http_code']}: $url");
    }
    
    // 偵測編碼並轉為 UTF-8
    $encoding = mb_detect_encoding($html, ['UTF-8', 'BIG5', 'GBK', 'ISO-8859-1'], true);
    if ($encoding && $encoding !== 'UTF-8') {
        $html = mb_convert_encoding($html, 'UTF-8', $encoding);
    }
    
    // 修正 HTML 中的 charset 宣告
    $html = preg_replace('/charset\s*=\s*["\']?[^"\'>\s]+/i', 'charset="utf-8"', $html, 1);
    
    return $html;
}

完整爬蟲類別封裝

class LinkExtractor {
    private $baseUrl;
    private $dom;
    private $xpath;
    private $visited = [];
    
    public function __construct($url) {
        $this->baseUrl = $url;
        $html = fetchHtml($url);
        $this->dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $this->dom->loadHTML('<meta charset="utf-8">' . $html);
        libxml_clear_errors();
        $this->xpath = new DOMXPath($this->dom);
    }
    
    public function getAllLinks($selector = '//a[@href]') {
        $nodes = $this->xpath->query($selector);
        $links = [];
        foreach ($nodes as $node) {
            $href = $node->getAttribute('href');
            if ($href && !$this->isVisited($href)) {
                $links[] = [
                    'url' => $this->resolve($href),
                    'text' => trim($node->textContent),
                    'title' => $node->getAttribute('title'),
                ];
                $this->visited[$href] = true;
            }
        }
        return $links;
    }
    
    public function getInternalLinks() {
        return $this->getAllLinks('//a[@href and not(starts-with(@href, "http")) or contains(@href, "' . parse_url($this->baseUrl, PHP_URL_HOST) . '")]');
    }
    
    public function getExternalLinks() {
        return $this->getAllLinks('//a[@href and starts-with(@href, "http") and not(contains(@href, "' . parse_url($this->baseUrl, PHP_URL_HOST) . '"))]');
    }
    
    private function resolve($href) { /* 同前 resolveUrl */ }
    private function isVisited($url) { return isset($this->visited[$url]); }
}

效能優化建議

  • 並行請求:使用 curl_multi 或 GuzzleHttp\Pool 同時抓取多個 URL
  • 快取機制:Redis 快取 HTML 內容,設定 TTL (如 1 小時)
  • 限流禮儀:sleep(1) 或 Token Bucket 算法,尊重 robots.txt
  • 記憶體管理:大量頁面處理時定期 $dom = null; gc_collect_cycles();

法律與道德提醒

  • 遵守 robots.txt 爬蟲協議
  • 檢查網站 Terms of Service 是否禁止爬取
  • 不要對目標伺服器造成過大負載 (DoS 風險)
  • 個人資料/受版權保護內容勿儲存散布
  • 商業用途請取得授權或使用官方 API
copyright © 萬盛學電腦網 all rights reserved