首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 使用 DOMDocument 與 XPath 快速抓取網頁所有連結

     編輯:PHP 相關知識

前言

抓取網頁所有 `` 連結是爬蟲、SEO 分析、死連結檢測的基礎需求。PHP 內建 DOMDocument + DOMXPath 提供標準、健壯的 HTML 解析能力,避免正則表達式處理不完整/巢狀標籤的風險。

核心程式碼

<?php
$url = 'https://www.example.com';

// 1. 取得 HTML 內容(生產環境建議用 cURL 處理重導向、逾時、Cookie)
$html = file_get_contents($url);
if ($html === false) {
    die("無法取得頁面內容");
}

// 2. 建立 DOMDocument 並載入 HTML
$dom = new DOMDocument();
// 抑制不符標準 HTML 產生的警告
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();

// 3. 建立 XPath 查詢所有  元素
$xpath = new DOMXPath($dom);
$links = $xpath->query('//a[@href]'); // 只選擇有 href 屬性的 a 標籤

// 4. 遍歷輸出
foreach ($links as $link) {
    $href = $link->getAttribute('href');
    $text = trim($link->nodeValue);
    echo "URL: {$href} | 文字: {$text}\n";
}

進階 XPath 查詢技巧

需求XPath 表達式
所有連結(含無 href)//a
僅外部連結//a[starts-with(@href, 'http')]
特定 class 的連結//a[contains(@class, 'btn')]
排除錨點連結//a[@href and not(starts-with(@href, '#'))]

常見問題與解決

  • 相對路徑:抓到的 href 可能是 /path 或 ../page,需用 parse_url + 基礎 URL 組合成絕對路徑。
  • 編碼亂碼:loadHTML 預期 UTF-8,若來源為 Big5/GBK,需先 mb_convert_encoding($html, 'HTML-ENTITIES', '原編碼')。
  • 大型頁面記憶體:DOMDocument 會將整份文件載入記憶體,超大頁面建議改用 XMLReader 流式解析。
  • JavaScript 渲染內容:靜態解析無法取得 SPA 動態產生的連結,需搭配 Headless Chrome (Puppeteer/PHP-WebDriver)。

完整可執行範例(含相對路徑轉絕對)

function getAbsoluteLinks(string $url): array
{
    $html = @file_get_contents($url);
    if (!$html) return [];

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

    $xpath = new DOMXPath($dom);
    $anchors = $xpath->query('//a[@href]');

    $base = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST);
    $results = [];

    foreach ($anchors as $a) {
        $href = $a->getAttribute('href');
        // 簡易相對轉絕對
        if (strpos($href, 'http') !== 0) {
            $href = $base . ($href[0] === '/' ? '' : '/') . $href;
        }
        $results[] = [
            'url'  => $href,
            'text' => trim($a->nodeValue),
        ];
    }
    return $results;
}

// 使用
$links = getAbsoluteLinks('https://www.example.com');
print_r($links);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved