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

PHP 打造網頁資源抓取器:一鍵下載靜態頁面與 CSS、JS、圖片資源

     編輯:PHP 綜合知識

前言:為什麼需要網頁資源抓取工具?

在網頁開發中,我們經常會遇到這樣的場景:看到別人設計精美的頁面模板想參考,或者因時間緊迫來不及自行設計 UI。此時,一個能自動抓取目標網頁 HTML 結構、並完整下載其依賴的 CSS、JavaScript、字體與圖片資源的工具,就能大幅提升開發效率。本文將分享一套使用 PHP 實現的「網頁抓取器」,它能按相對路徑保存所有資源,避免資源路徑錯誤導致的載入失敗。

核心架構:三個檔案協同運作

此工具包含三個核心 PHP 檔案,分工明確:

  • index.php:前端操作介面,輸入專案名稱與目標網址。
  • grab.php:核心抓取邏輯,解析 HTML 並提取資源連結。
  • save.php:資源儲存處理,按相對路徑建立目錄並下載檔案。

index.php:直觀的操作介面

這是一個簡單的 HTML 表單,引入了 jQuery 與自訂樣式/腳本:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>網頁抓取器</title>
  <link rel="stylesheet" href="main.css">
  <script src="jquery.js"></script>
  <script src="main.js"></script>
</head>
<body>
  <h1>Web Grabber</h1>
  <div class="box">
    <h2>目標網址</h2>
    <div class="form">
      <input type="text" id="project" value="projectname" placeholder="專案名稱">
      <input type="text" id="url" value="https://" size="60" placeholder="請輸入完整網址(需以檔名結尾,如 index.html)">
      <button class="submit" type="button">Get</button>
      <span id="tip"></span>
    </div>
  </div>
  <div class="box">
    <span class="all" id="saveall">Save All</span>
    <h2>資源列表</h2>
    <ul id="list"></ul>
  </div>
</body>
</html>

grab.php:智慧解析與資源提取

此檔案接收前端傳來的 URL,使用 file_get_contents 取得網頁內容,再透過正規表示式提取 CSS、JS、圖片與 CSS 中的 url() 資源:

<?php
if (isset($_POST['url'])) {
    if (isset($_POST['project']) && !is_dir($_POST['project'])) {
        mkdir($_POST['project'], 0777, true);
    }
    echo json_encode(grab($_POST['url']));
}

function grab($url) {
    $data = [];
    $file = preg_replace('/^.*\//', '', $url); // 取得檔名

    if (($content = @file_get_contents($url)) !== false) {
        // 儲存主 HTML
        if (isset($_POST['project'])) {
            file_put_contents($_POST['project'] . '/' . $file, $content);
        }

        // 提取 CSS
        if (preg_match_all('/<link[^>]*href=([\'"])(.*?\.css)\\1[^>]*>/i', $content, $matches)) {
            $data['css'] = $matches[2];
        }
        // 提取 JS
        if (preg_match_all('/<script[^>]*src=([\'"])(.*?\.js)\\1[^>]*>/i', $content, $matches)) {
            $data['js'] = $matches[2];
        }
        // 提取圖片
        if (preg_match_all('/<img[^>]*src=([\'"])(.*?)\\1[^>]*>/i', $content, $matches)) {
            $data['img'] = $matches[2];
        }
        // 提取 CSS 中的 url() 資源(背景圖、字體等)
        if (preg_match_all('/url\(([\'"]?)(.*?)\\1\)/i', $content, $matches)) {
            $data['src'] = $matches[2];
        }
    }
    return $data;
}
?>

save.php:依相對路徑精準儲存

此檔案處理實際下載與儲存,支援遠端絕對路徑與相對路徑,自動建立多層目錄:

<?php
if (isset($_POST['url'], $_POST['project'], $_POST['domain'])) {
    extract($_POST);
    $url = preg_replace('/\?.*$/', '', $url); // 移除查詢字串
    $file = $url;
    $arr = explode('/', $file);
    $filename = end($arr);
    $root = $project;
    $dir = $root;

    if ($domain === 'http') {
        // 遠端資源統一存放於 http 資料夾
        $dir = $root . '/http';
        if (!is_dir($dir)) mkdir($dir, 0777, true);
    } else {
        // 相對路徑:重建目錄結構
        $file = $domain . '/' . $url;
        for ($i = 0; $i < count($arr) - 1; $i++) {
            if (!empty($arr[$i])) {
                $dir .= '/' . $arr[$i];
                if (!is_dir($dir)) mkdir($dir, 0777, true);
            }
        }
    }

    // 避免重複下載空檔案
    if (!file_exists($dir . '/' . $filename) || filesize($dir . '/' . $filename) == 0) {
        $content = @file_get_contents($file);
        if ($content !== false) {
            file_put_contents($dir . '/' . $filename, $content);
        }
    }
}
?>

操作流程指南

  1. 開啟 index.php,輸入專案名稱與目標網址(網址必須以檔名結尾,如 index.html)。
  2. 點擊 Get 按鈕,系統會解析頁面並列出所有 CSS、JS、圖片資源。
  3. 點擊 CSS 連結可進一步提取該 CSS 檔案中的背景圖片資源。
  4. 點擊 Save All 即可一次性下載所有資源,並自動依相對路徑建立目錄結構。
  5. 遠端資源(以 https:// 開頭)會統一存放在專案下的 http/ 目錄。
  6. 若偶發網路抓取失敗,重試幾次通常即可成功。

進階應用與注意事項

  • 編碼處理:若目標頁面非 UTF-8,建議搭配 mb_convert_encoding 轉碼。
  • 大檔案支援:針對大型資源,可改用 cURL 分塊下載,避免記憶體耗盡。
  • 法律合規:僅供學習研究或取得授權之模板參考,請勿用於未經授權的商業用途。
  • 擴充功能:可加入資源壓縮(CSS/JS minify)、圖片優化、自動修正 HTML 中資源路徑等功能。

總結

這套 PHP 網頁抓取器雖然程式碼精簡,卻涵蓋了 HTTP 取得、正規表示式解析、遞迴建目錄、檔案儲存等核心技術。它不僅能幫助開發者快速獲取前端模板,更是理解 PHP 檔案操作與網路請求的優秀實戰範例。希望能為你的專案開發帶來啟發與便利。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved