在網頁開發中,我們經常會遇到這樣的場景:看到別人設計精美的頁面模板想參考,或者因時間緊迫來不及自行設計 UI。此時,一個能自動抓取目標網頁 HTML 結構、並完整下載其依賴的 CSS、JavaScript、字體與圖片資源的工具,就能大幅提升開發效率。本文將分享一套使用 PHP 實現的「網頁抓取器」,它能按相對路徑保存所有資源,避免資源路徑錯誤導致的載入失敗。
此工具包含三個核心 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>
此檔案接收前端傳來的 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;
}
?>
此檔案處理實際下載與儲存,支援遠端絕對路徑與相對路徑,自動建立多層目錄:
<?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);
}
}
}
?>
index.php,輸入專案名稱與目標網址(網址必須以檔名結尾,如 index.html)。http/ 目錄。mb_convert_encoding 轉碼。這套 PHP 網頁抓取器雖然程式碼精簡,卻涵蓋了 HTTP 取得、正規表示式解析、遞迴建目錄、檔案儲存等核心技術。它不僅能幫助開發者快速獲取前端模板,更是理解 PHP 檔案操作與網路請求的優秀實戰範例。希望能為你的專案開發帶來啟發與便利。