Skip to content

Instantly share code, notes, and snippets.

@joey-g
Last active April 26, 2024 23:17
Show Gist options
  • Save joey-g/9a57d02b62548218963905c686c76022 to your computer and use it in GitHub Desktop.
Save joey-g/9a57d02b62548218963905c686c76022 to your computer and use it in GitHub Desktop.
Headless Chrome - WebDriver Example
// https://developers.google.com/web/updates/2017/04/headless-chrome
const fs = require('fs');
const {Builder, By, Capabilities, Key, until} = require('selenium-webdriver');
const chromedriver = require('chromedriver');
const chromeCapabilities = Capabilities.chrome();
chromeCapabilities.set('chromeOptions', {args: ['--headless']});
async function test() {
// Note: On macOS, you'll likely see a new Chrome process flash on your 'Dock'
// when this new driver object is built. As it's launched headlessly, it's
// expected behavior for it to be removed from the dock.
let driver = await new Builder()
.forBrowser('chrome')
.withCapabilities(chromeCapabilities)
.build();
try {
await driver.get('https://www.google.com');
await driver.findElement(By.name('q')).sendKeys('webdriver');
// Take a new screenshot and drop it in the current directory.
await driver.takeScreenshot().then(base64png => {
fs.writeFileSync('screenshot.png', new Buffer(base64png, 'base64'));
});
} finally {
await driver.quit();
}
}
test();
npm install selenium-webdriver
npm install chromedriver
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment