有没有办法在 Selenium 版本 4 和更高版本中以无头模式执行 UI 测试?

Is there any way to execute the UI tests in headless mode in Selenium version 4 and heigher?

最近 Selenium 发布了他们的主要版本 Selenium 4,并宣布从 Selenium4 开始将不再支持 PhantomJS。这是否意味着 Selenium 不再支持无头自动化,或者是否有任何方法可以在 Selenium 版本 4 中以无头模式执行测试?欣赏代码示例。

在 Selenium 4 中,删除了对 PhantomJS 的原生支持。不过,使用 PhantomJS 运行 无头模式脚本的用户可以在无头模式下使用 Chrome 或 Firefox,如下所示。

const chrome = require('../chrome');
const firefox = require('../firefox');
const {Builder, By, Key, until} = require('..');

const width = 640;
const height = 480;

let driver = new Builder()
    .forBrowser('chrome')
    .setChromeOptions(
        new chrome.Options().headless().windowSize({width, height}))
    .setFirefoxOptions(
        new firefox.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; }));

要了解有关 Selenium 4 更改的更多信息,请参阅 Selenium 4 (alpha) is Released: What’s New?