[英]Execute single Javascript file with headless chrome from the command line
我們使用 PhantomJS 作為簡單的測試運行器,如下所示:
phantomjs path/to/test.js
無頭鍍鉻有類似的方法嗎?
Selenium WebDriver是一個 NPM 包,可以幫助您運行無頭瀏覽器。
試試下面的例子:
const chrome = require('selenium-webdriver/chrome');
const {Builder, By, Key, until} = require('selenium-webdriver');
const width = 640;
const height = 480;
let driver = new Builder()
.forBrowser('chrome')
.setChromeOptions(
new chrome.Options().headless().windowSize({width, height}))
.build();
driver.get('http://www.google.com/ncr')
.then(_ =>
driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN))
.then(_ => driver.wait(until.titleIs('webdriver - Google Search'), 1000))
.then(
_ => driver.quit(),
e => driver.quit().then(() => { throw e; }));
根據API ,驅動方法返回 Promises,因此可以使用async
/ await
語法調用:
const chrome = require('selenium-webdriver/chrome');
const {Builder, By, Key, until} = require('selenium-webdriver');
async function test() {
const width = 640;
const height = 480;
let driver = new Builder()
.forBrowser('chrome')
.setChromeOptions(
new chrome.Options().headless().windowSize({width, height}))
.build();
await driver.get('http://www.google.com/ncr')
await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN))
await driver.wait(until.titleIs('webdriver - Google Search'), 1000))
await driver.quit()
}
test();
正如developers.google 上所解釋的,您可以選擇使用Node
或Selenium
,在任何一種情況下,您都必須重新編寫部分測試用例以使用新的 api 而不是phantomjs
api 。
以下選項基於Node
:
我建議您前往他們的github 頁面獲取安裝和使用說明。
您的測試用例應該使用Puppetteer
api編寫並運行:
node path/to/test.js
有一個puppeteer 資源列表,您可以使用puppeteer
與jest
、 mocha
、 angular
、 e2e
..
chrome-remote-interface是比 Puppeteer 的 API 低級的庫。 如果你想接近金屬並直接使用 DevTools 協議,我推薦它。
您需要以無頭模式啟動chrome
或使用lighthouse
或nodejs
:
node --inspect=9222 path/to/test.js
使用chrome DevTools protocol
編寫您的javascript
測試用例,並按照他們的 github 頁面上的說明安裝和運行您的測試。
另一種選擇是使用配置 為運行無頭 Chrome的Selenium
。 以下選項使用Selenium
:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.