PhantomJS 是一個以 WebKit 為核心的伺服器端 JavaScript API。它不需要完整的瀏覽器介面就能支援各項 Web 標準——DOM 操作、CSS 選擇器、JSON、Canvas、SVG 全部原生可用。因為夠快、夠完整,它常被用於網頁自動化、資源監控、網頁截圖與無介面測試等場景。
官網:https://phantomjs.org/
GitHub:https://github.com/ariya/phantomjs/wiki/Quick-Start
下載頁面:https://phantomjs.org/download.html,提供 Windows、Mac OS 與 Linux 版本。選擇對應平台下載解壓即可,建議自行設定環境變數以便使用。壓縮檔內附一個 example 目錄,裡頭有不少現成範例可直接參考。以下假設已完成安裝並設定好環境變數。
Hello, world!
建立一個文字檔,寫入兩行:
console.log('Hello, world!');
phantom.exit();
另存為 hello.js,然後執行:
phantomjs hello.js
輸出:
Hello, world!
第一行在終端機印出字串,第二行讓 PhantomJS 結束執行。這裡要特別強調:呼叫 phantom.exit() 非常重要,否則 PhantomJS 不會自行停止。
執行時可以傳入參數:
phantomjs examples/arguments.js foo bar baz
在腳本中透過 system 模組取得:
var system = require('system');
if (system.args.length === 1) {
console.log('Try to pass some args when invoking this script!');
} else {
system.args.forEach(function (arg, i) {
console.log(i + ': ' + arg);
});
}
phantom.exit();
輸出:
0: foo 1: bar 2: baz
注意索引從 0 開始,而 system.args[0] 是腳本名稱,因此 length === 1 代表「沒有傳入額外參數」。
透過建立網頁物件,就能載入、分析並渲染一個頁面。最簡單的用法如下,它載入 example.com 並存成 example.png:
var page = require('webpage').create();
page.open('https://example.com', function () {
page.render('example.png');
phantom.exit();
});
由於具備這個能力,PhantomJS 很適合用來做網頁快照——把頁面、SVG 存成圖片或 PDF,都是幾行程式碼的事。
接著看一個實用一點的例子,loadspeed.js 用來計量表單頁面的載入時間:
var page = require('webpage').create(),
system = require('system'),
t, address;
if (system.args.length === 1) {
console.log('Usage: loadspeed.js <some URL>');
phantom.exit();
}
t = Date.now();
address = system.args[1];
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
} else {
t = Date.now() - t;
console.log('Loading time ' + t + ' msec');
}
phantom.exit();
});
執行:
phantomjs loadspeed.js https://www.google.com
輸出類似:
Loading https://www.google.com Loading time 719 msec
要在網頁的執行環境中運算 JavaScript 或 CoffeeScript,使用 evaluate()。要注意它是在一個「沙箱」中執行的:無法讀取所屬頁面上下文之外的 JavaScript 物件與變數,回傳值也只能是簡單物件,不能包含方法或閉包。
取得頁面標題:
var page = require('webpage').create();
page.open(url, function (status) {
var title = page.evaluate(function () {
return document.title;
});
console.log('Page title is ' + title);
});
頁面內部的 console.log 預設不會顯示在終端機。若想攔截,改用 onConsoleMessage 回呼:
var page = require('webpage').create();
page.onConsoleMessage = function (msg) {
console.log('Page title is ' + msg);
};
page.open(url, function (status) {
page.evaluate(function () {
console.log(document.title);
});
});
因為腳本執行環境就像一個真正的瀏覽器,標準的 DOM 操作與 CSS 選擇器都能正常運作,這讓 PhantomJS 特別適合各類網頁自動化任務。
以下 useragent.js 讀取 id 為 myagent 元素的 textContent,同時示範如何自訂 user agent:
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('https://www.httpuseragent.org', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementById('myagent').textContent;
});
console.log(ua);
}
phantom.exit();
});
引入 jQuery 等外部函式庫也很容易,用 includeJs 即可:
var page = require('webpage').create();
page.open('https://www.sample.com', function () {
page.includeJs("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
page.evaluate(function () {
$("button").click();
});
phantom.exit();
});
});
當頁面從遠端伺服器請求資源時,請求與回應都能透過 onResourceRequested 與 onResourceReceived 兩個回呼攔截,這是做效能分析與除錯時非常有用的一組工具:
var page = require('webpage').create();
page.onResourceRequested = function (request) {
console.log('Request ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function (response) {
console.log('Receive ' + JSON.stringify(response, undefined, 4));
};
page.open(url);
把這些資料整理成 HAR 格式輸出,再搭配 YSlow 進行分析,就能產出完整的頁面效能報告。
需要補充的是,PhantomJS 的開發已在 2018 年正式停止。由於 WebKit 版本停留在 2013 年左右,它無法正確執行依賴 ES6 及以上特性的現代網站,這是實務上必須考量的限制。
現今若要進行無介面瀏覽器自動化,主流選擇是 Puppeteer 與 Playwright,兩者底層使用真實的 Chromium,對現代 Web 標準支援完整,API 設計也更貼近當代語法(async/await)。PhantomJS 的價值如今主要在歷史理解與維護既有腳本;但它「以程式控制瀏覽器」的核心概念,與今日的工具一脈相承,讀懂這份入門仍有助於快速上手後繼者。