重點摘要
Chrome 59 推出 Headless Chrome 一文。這是在無頭環境中執行 Chrome 瀏覽器的方法。 基本上,不帶 Chrome 就能執行 Chrome!這個程式庫可將 Chromium 和 Blink 轉譯引擎提供的所有新式網路平台功能導入指令列。
為什麼這個實用?
無頭瀏覽器非常適合用於自動化測試和伺服器環境,非常適合不需要可見的 UI 殼層。例如,您可能會想對實際網頁執行一些測試、建立 PDF 檔案,或只檢查瀏覽器轉譯網址的方式。
開始無頭 (CLI)
如要開始使用無頭模式,最簡單的方法是透過指令列開啟 Chrome 二進位檔。如果已安裝 Chrome 59 以上版本,請使用 --headless
標記啟動 Chrome:
chrome \
--headless \ # Runs Chrome in headless mode.
--disable-gpu \ # Temporarily needed if running on Windows.
--remote-debugging-port=9222 \
https://www.chromestatus.com # URL to open. Defaults to about:blank.
chrome
應指向安裝的 Chrome。確切位置會因平台而異。由於我是 Mac,我為已安裝的每個 Chrome 版本
都建立方便的別名
如果您的 Chrome 穩定版無法使用測試版,建議您使用 chrome-canary
:
alias chrome="/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"
alias chrome-canary="/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary"
alias chromium="/Applications/Chromium.app/Contents/MacOS/Chromium"
在這裡下載 Chrome Canary。
指令列功能
在某些情況下,您可能不需要程式輔助指令碼,即可使用 Headless Chrome。 您可以使用一些實用的指令列標記來執行常見工作。
列印 DOM
--dump-dom
標記會將 document.body.innerHTML
列印至 stdout:
chrome --headless --disable-gpu --dump-dom https://www.chromestatus.com/
建立 PDF
--print-to-pdf
標記會建立頁面的 PDF 檔案:
chrome --headless --disable-gpu --print-to-pdf https://www.chromestatus.com/
擷取螢幕畫面
如要擷取網頁的螢幕截圖,請使用 --screenshot
標記:
chrome --headless --disable-gpu --screenshot https://www.chromestatus.com/
# Size of a standard letterhead.
chrome --headless --disable-gpu --screenshot --window-size=1280,1696 https://www.chromestatus.com/
# Nexus 5x
chrome --headless --disable-gpu --screenshot --window-size=412,732 https://www.chromestatus.com/
如果透過 --screenshot
執行,系統會在目前的工作目錄中產生名為 screenshot.png
的檔案。如果需要整頁的螢幕擷取畫面有一篇 David Schnurr 撰寫的
實用網誌文章提到了請參閱「使用無頭 Chrome 做為自動化螢幕截圖工具 」一文。
REPL 模式 (讀取-eval-print 迴圈)
--repl
標記會在模式中執行 Headless,直接透過指令列評估瀏覽器中的 JS 運算式:
$ chrome --headless --disable-gpu --repl --crash-dumps-dir=./tmp https://www.chromestatus.com/
[0608/112805.245285:INFO:headless_shell.cc(278)] Type a Javascript expression to evaluate or "quit" to exit.
>>> location.href
{"result":{"type":"string","value":"https://www.chromestatus.com/features"}}
>>> quit
$
不使用瀏覽器使用者介面對 Chrome 進行偵錯嗎?
使用 --remote-debugging-port=9222
執行 Chrome 時,系統會啟動已啟用 DevTools 通訊協定的執行個體。通訊協定的用途是與 Chrome 通訊,並驅動無頭瀏覽器執行個體。以及 Sublime、VS Code 和 Node 等工具,用於遠端偵錯應用程式。#synergy
由於沒有瀏覽器 UI 可以查看網頁,因此請使用其他瀏覽器前往 http://localhost:9222
,確認一切運作正常。您會看到可檢查的網頁清單,可供點選,並查看無頭介面轉譯的是哪些網頁:
您可以在此使用熟悉的開發人員工具功能,照常檢查、偵錯及調整頁面。如果您是以程式輔助方式使用 Headless,這個頁面也是功能強大的偵錯工具,可用於查看傳輸的所有原始 DevTools 通訊協定指令並與瀏覽器通訊。
透過程式輔助方式使用 (節點)
布偶操作員
Puppeteer 是由 Chrome 團隊開發的節點程式庫,並提供用於控制無頭 (或完整) Chrome 的高階 API。這項工具類似於 Phantom 和 NightmareJS 等其他自動化測試程式庫,但僅支援最新版本的 Chrome。
此外,Puppeteer 還能用來輕鬆拍攝螢幕截圖、建立 PDF、瀏覽頁面及擷取網頁相關資訊。如要快速自動執行瀏覽器測試,建議您使用這個程式庫。這項工具不會顯示開發人員工具通訊協定的複雜性,並處理不必要的工作,例如啟動 Chrome 的偵錯執行個體。
安裝:
npm i --save puppeteer
範例 - 列印使用者代理程式
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
console.log(await browser.version());
await browser.close();
})();
例如:擷取頁面的螢幕截圖
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.chromestatus.com', {waitUntil: 'networkidle2'});
await page.pdf({path: 'page.pdf', format: 'A4'});
await browser.close();
})();
如要進一步瞭解完整 API,請參閱 Puppeteer 的說明文件。
CRI 程式庫
chrome-remote-interface 是比 Puppeteer API 低階的程式庫。如果您想靠近金屬,並直接使用開發人員工具通訊協定,建議您採用這種做法。
正在啟動 Chrome
chrome-remote-interface 不會為您啟動 Chrome,因此您必須自行完成。
在 CLI 部分中,我們使用 --headless --remote-debugging-port=9222
手動啟動 Chrome。不過,若要完全自動化測試,您可能需要「從」應用程式產生 Chrome。
其中一種方法是使用 child_process
:
const execFile = require('child_process').execFile;
function launchHeadlessChrome(url, callback) {
// Assuming MacOSx.
const CHROME = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome';
execFile(CHROME, ['--headless', '--disable-gpu', '--remote-debugging-port=9222', url], callback);
}
launchHeadlessChrome('https://www.chromestatus.com', (err, stdout, stderr) => {
...
});
但是,如果想要一個適用於多個平台的可攜式解決方案,操作起來可能相當棘手。只要查看這個硬式編碼的 Chrome 路徑 :(
使用 ChromeLauncher
Lighthouse 是測試網路應用程式品質的絕佳工具。系統已在 Lighthouse 中開發用於啟動 Chrome 的完善模組,現在可單獨使用。chrome-launcher
NPM 模組會尋找 Chrome 的安裝位置、設定偵錯執行個體、啟動瀏覽器,並在程式完成時終止瀏覽器。最棒的是,這個 API 可以跨平台運作,都要歸功於 Node!
根據預設,chrome-launcher
會嘗試啟動 Chrome Canary (如果已安裝),但您可以更改設定,手動選取要使用的 Chrome。如要使用,請先從 npm 安裝:
npm i --save chrome-launcher
範例 - 使用 chrome-launcher
啟動 Headless
const chromeLauncher = require('chrome-launcher');
// Optional: set logging level of launcher to see its output.
// Install it using: npm i --save lighthouse-logger
// const log = require('lighthouse-logger');
// log.setLevel('info');
/**
* Launches a debugging instance of Chrome.
* @param {boolean=} headless True (default) launches Chrome in headless mode.
* False launches a full version of Chrome.
* @return {Promise<ChromeLauncher>}
*/
function launchChrome(headless=true) {
return chromeLauncher.launch({
// port: 9222, // Uncomment to force a specific port of your choice.
chromeFlags: [
'--window-size=412,732',
'--disable-gpu',
headless ? '--headless' : ''
]
});
}
launchChrome().then(chrome => {
console.log(`Chrome debuggable on port: ${chrome.port}`);
...
// chrome.kill();
});
執行這個指令碼不太容易,但您應該會在載入 about:blank
的工作管理員中看到 Chrome 的啟動例項。請注意,系統不會提供任何瀏覽器 UI,我們不是頭緒。
如要控制瀏覽器,我們需要開發人員工具通訊協定!
擷取網頁相關資訊
請安裝程式庫:
npm i --save chrome-remote-interface
示例
範例 - 列印使用者代理程式
const CDP = require('chrome-remote-interface');
...
launchChrome().then(async chrome => {
const version = await CDP.Version({port: chrome.port});
console.log(version['User-Agent']);
});
結果如:HeadlessChrome/60.0.3082.0
範例:檢查網站是否有網頁應用程式資訊清單
const CDP = require('chrome-remote-interface');
...
(async function() {
const chrome = await launchChrome();
const protocol = await CDP({port: chrome.port});
// Extract the DevTools protocol domains we need and enable them.
// See API docs: https://chromedevtools.github.io/devtools-protocol/
const {Page} = protocol;
await Page.enable();
Page.navigate({url: 'https://www.chromestatus.com/'});
// Wait for window.onload before doing stuff.
Page.loadEventFired(async () => {
const manifest = await Page.getAppManifest();
if (manifest.url) {
console.log('Manifest: ' + manifest.url);
console.log(manifest.data);
} else {
console.log('Site has no app manifest');
}
protocol.close();
chrome.kill(); // Kill Chrome.
});
})();
範例 - 使用 DOM API 擷取網頁的 <title>
。
const CDP = require('chrome-remote-interface');
...
(async function() {
const chrome = await launchChrome();
const protocol = await CDP({port: chrome.port});
// Extract the DevTools protocol domains we need and enable them.
// See API docs: https://chromedevtools.github.io/devtools-protocol/
const {Page, Runtime} = protocol;
await Promise.all([Page.enable(), Runtime.enable()]);
Page.navigate({url: 'https://www.chromestatus.com/'});
// Wait for window.onload before doing stuff.
Page.loadEventFired(async () => {
const js = "document.querySelector('title').textContent";
// Evaluate the JS expression in the page.
const result = await Runtime.evaluate({expression: js});
console.log('Title of page: ' + result.result.value);
protocol.close();
chrome.kill(); // Kill Chrome.
});
})();
使用 Selenium、WebDriver 和 ChromeDriver
Selenium 現已開啟完整的 Chrome 執行個體。換句話說,這是自動化解決方案 但不是完全無頭不過,Selenium 可以透過設定來執行無頭 Chrome,只要稍加修改即可。如需如何自行設定的完整操作說明,建議您搭配 Headless Chrome 執行 Selenium,不過以下提供部分範例,供您參考。
使用 ChromeDriver
ChromeDriver 2.32 使用 Chrome 61,且能與無頭 Chrome 搭配使用。
安裝:
npm i --save-dev selenium-webdriver chromedriver
示例:
const fs = require('fs');
const webdriver = require('selenium-webdriver');
const chromedriver = require('chromedriver');
const chromeCapabilities = webdriver.Capabilities.chrome();
chromeCapabilities.set('chromeOptions', {args: ['--headless']});
const driver = new webdriver.Builder()
.forBrowser('chrome')
.withCapabilities(chromeCapabilities)
.build();
// Navigate to google.com, enter a search.
driver.get('https://www.google.com/');
driver.findElement({name: 'q'}).sendKeys('webdriver');
driver.findElement({name: 'btnG'}).click();
driver.wait(webdriver.until.titleIs('webdriver - Google Search'), 1000);
// Take screenshot of results page. Save to disk.
driver.takeScreenshot().then(base64png => {
fs.writeFileSync('screenshot.png', new Buffer(base64png, 'base64'));
});
driver.quit();
使用 WebDriverIO
WebDriverIO 是位於 Selenium WebDriver 之上的更高階 API。
安裝:
npm i --save-dev webdriverio chromedriver
例如:在 chromestatus.com 篩選 CSS 功能
const webdriverio = require('webdriverio');
const chromedriver = require('chromedriver');
const PORT = 9515;
chromedriver.start([
'--url-base=wd/hub',
`--port=${PORT}`,
'--verbose'
]);
(async () => {
const opts = {
port: PORT,
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {args: ['--headless']}
}
};
const browser = webdriverio.remote(opts).init();
await browser.url('https://www.chromestatus.com/features');
const title = await browser.getTitle();
console.log(`Title: ${title}`);
await browser.waitForText('.num-features', 3000);
let numFeatures = await browser.getText('.num-features');
console.log(`Chrome has ${numFeatures} total features`);
await browser.setValue('input[type="search"]', 'CSS');
console.log('Filtering features...');
await browser.pause(1000);
numFeatures = await browser.getText('.num-features');
console.log(`Chrome has ${numFeatures} CSS features`);
const buffer = await browser.saveScreenshot('screenshot.png');
console.log('Saved screenshot...');
chromedriver.stop();
browser.end();
})();
其他資源
以下提供幾項實用資源,協助您快速上手:
文件
- 開發人員工具通訊協定檢視者 - API 參考文件
工具
- chrome-remote-interface - 納入開發人員工具通訊協定的節點模組
- Lighthouse:用於測試網頁應用程式品質的自動化工具;大量使用通訊協定
- chrome-launcher - 用於啟動 Chrome 的節點模組,隨時支援自動化功能
試聽帶
- 「Headless Web」(無頭網頁) - Paul Kinlan 的正面網誌文章,說明瞭如何將 Headless 和 api.ai 搭配使用。
常見問題
我需要 --disable-gpu
旗標嗎?
僅限 Windows。其他平台不再需要使用這項功能。--disable-gpu
標記是暫時處理一些錯誤的問題。在日後的 Chrome 版本中,您不需要使用這個旗標。詳情請參閱 crbug.com/737678 的說明。
所以我還需要 Xvfb 嗎?
否。無頭 Chrome 不會使用視窗,因此不再需要像 Xvfb 的顯示伺服器。輕鬆執行自動化測試。
Xvfb 是什麼?Xvfb 是一個記憶體內顯示伺服器,適用於類似 Unix 的系統,可讓您在不連接實體螢幕的情況下執行圖形應用程式 (例如 Chrome)。許多人會使用 Xvfb 執行舊版 Chrome 來進行「無頭」測試。
如何建立執行 Headless Chrome 的 Docker 容器?
查看 lighthouse-ci。這個範例有 Dockerfile 使用 node:8-slim
做為基本映像檔,並在 App Engine Flex 上安裝 + 執行 Lighthouse。
這項服務可以搭配 Selenium / WebDriver / ChromeDriver 使用嗎?
是,請參閱使用 Selenium、WebDriver 和 ChromeDriver。
這與 PhantomJS 有何關聯?
無頭 Chrome 與 PhantomJS 等工具類似。兩者都可用於在無頭環境中的自動化測試。兩者的主要差異在於,Phantom 使用舊版 WebKit 做為算繪引擎,而 Headless Chrome 則使用最新版的 Blink。
目前 Phantom 提供的 API 級別比開發人員工具通訊協定來得高。
該到哪裡回報錯誤?
如果是針對 Headless Chrome 的錯誤,請前往 crbug.com 回報。
如果是開發人員工具通訊協定中的錯誤,請前往 github.com/ChromeDevTools/devtools-protocol 回報。