離線瀏覽器本質是網站鏡像工具 + 本地渲染引擎。關鍵難點:超連結重寫——將 HTML 中的絕對 URL 轉換為本地路徑,相對路徑保持不變,使離線瀏覽時點擊連結能正確定位本地檔案。
規則:本地根目錄 / 協定_主機IP/埠 / 遠端目錄路徑 / 檔名
範例:
URL: https://11.171.38.32/webfile/relax/index.html
本地根目錄: /home/user/web
鏡像路徑: /home/user/web/http_11.171.38.32/webfile/relax/index.html
關鍵點:主機名需解析為 IP (用 gethostbyname()),避免同一伺服器不同域名產生重複鏡像目錄。
KURL u(url_string);
QString protocol = u.protocol(); // "http"
QString host = u.host(); // "example.com" 或 IP
QString path = u.path(); // "/webfile/relax/index.html"
QString file = u.fileName(); // "index.html"
QString dir = u.directory(); // "/webfile/relax/" (含尾斜線)
KURL 不支援查詢字串做檔名。需自行擴展:
QString query = u.query(); // "id=123&action=view"
// 策略:將查詢字串編碼為檔名一部分
QString safe_query = query.replace('&', '_').replace('=', '-');
QString file = u.fileName() + "_" + safe_query + ".html"; // index.html_id-123_action-view.html
QString generateLocalPath(const QString &baseDir, const KURL &url) {
QString ip = resolveHostToIP(url.host()); // gethostbyname()
QString protocol = url.protocol();
QString dir = url.directory(); // 含尾斜線
QString file = url.fileName();
if (file.isEmpty()) file = "index.html"; // 目錄預設檔
QString localDir = baseDir + "/" + protocol + "_" + ip + dir;
return localDir + file;
}
Linux mkdir() 僅能建立單層目錄,需遞迴實現 mkdir -p。
int mkdir_p(const QString &path, mode_t mode = 0755) {
if (path.isEmpty()) return -1;
// 已存在直接成功
if (QFile::exists(path)) return 0;
// 遞迴建立父目錄
KURL u(path);
QString parent = u.directory(false); // 不含尾斜線的父目錄
if (mkdir_p(parent, mode) != 0) return -1;
// 建立自身
QByteArray ba = path.toLocal8Bit();
if (::mkdir(ba.constData(), mode) == -1 && errno != EEXIST) {
return -1;
}
return 0;
}
libxml2、Gumbo、或簡單正則)。<a href=...>, <img src=...>, <link href=...>, <script src=...>:QString rewriteLinks(const QString &html, const QString &baseUrl, const QString &localBaseDir) {
KURL base(baseUrl);
QString result = html;
// 簡易正則匹配 href/src 屬性 (實際建議用 HTML 解析器)
QRegExp rx("(href|src)\\s*=\\s*[\"']([^\"']+)[\"']");
int pos = 0;
while ((pos = rx.indexIn(result, pos)) != -1) {
QString attr = rx.cap(1);
QString url = rx.cap(2);
KURL u(url);
if (u.isRelative()) {
// 相對路徑:解析為相對於 base 的絕對 URL,再轉本地
u = base.resolved(url);
}
// 現在 u 是絕對 URL
QString localPath = generateLocalPath(localBaseDir, u);
// 轉為相對於當前 HTML 檔案的相對路徑 (更健壯)
QString relPath = QFileInfo(localPath).absoluteFilePath(); // 簡化:用絕對路徑
result.replace(rx.pos(2), rx.cap(2).length(), relPath);
pos += relPath.length();
}
return result;
}
KDE KHTMLPart/KHTMLView 提供完整 HTML 渲染引擎 (WebKit 前身)。
class CHtmlView : public KHTMLView {
public:
int showPage(const char *localPath) {
if (!localPath) return -1;
FILE *fp = fopen(localPath, "rb");
if (!fp) return -1;
begin(KURL::fromPathOrURL(localPath).directoryURL()); // 初始化 base URL
char buf[0x10000];
size_t len;
while ((len = fread(buf, 1, sizeof(buf), fp)) > 0) {
write(buf, len); // 寫入 KHTML 解析器緩衝區
}
fclose(fp);
end(); // 結束輸入
parse(); // 解析 HTML/CSS
show(); // 顯示
return 0;
}
// 處理滑鼠點擊超連結
bool mousePressedHook(const char *url, const char *target,
QMouseEvent *ev, bool selected) {
KHTMLView::mousePressedHook(url, target, ev, selected);
// url 已經是重寫後的本地路徑 (或相對路徑)
showPage(url);
return true;
}
};
// View 建構函數
CHtmlView *m_htmlview = new CHtmlView(this, "HtmlViewer");
m_htmlview->showPage("/home/user/web/http_11.171.38.32/index.html");
| 工具/框架 | 語言 | 特點 |
|---|---|---|
| httrack | C | 成熟 CLI/GUI 離線瀏覽器、支援 JavaScript 執行、表單、鏡像更新 |
| wget -mkEpnp | C | 單指令鏡像站點、-k 轉換連結、-p 下載嵌入資源 |
| Scrapy | Python | 強大爬蟲框架、非同步、中介軟體、Item Pipeline、可定製導出 |
| Puppeteer / Playwright | Node.js | Headless Chrome/Firefox、完整 JS 執行、SPA 支援、截圖/PDF |
| SingleFile (瀏覽器擴充) | JS | 單一 HTML 檔案封裝完整頁面 (含 CSS/JS/圖片 Base64) |