Install the WebDrivers.
Firefox on Ubuntu Linux:
sudo apt install firefox-geckodriverChrome on Ubuntu Linux:
sudo apt install chromium-chromedriverCreate a new node project and install the selenium-webdriver:
npm install --save selenium-webdriverTODO.
A skeleton selenium-webdriver setup using Firefox:
const {Builder, By, Key, until} = require('selenium-webdriver');
(async function skeleton() {
let driver = await new Builder().forBrowser('firefox').build();
try {
await driver.get('https://example.com/');
await driver.wait(until.titleIs('Example Title'), 2000);
} finally {
await driver.quit();
}
})();Default:
const browser = await new Builder().forBrowser('chrome');
const driver = await browser.build();With options (notice the goog:chromeOptions key):
// Chrome with options -
const chromeOpts = {
args: [
'--start-maximized',
'--use-fake-ui-for-media-stream'
],
};
let chromeCaps = Capabilities.chrome();
// Specify both options for grid or local use, see:
// https://github.com/webdriverio/webdriverio/issues/2645#issuecomment-407034467
chromeCaps = {
...chromeCaps,
'browserName': 'chrome',
'chromeOptions': chromeOpts,
'goog:chromeOptions': chromeOpts,
};
const driver = await new Builder().withCapabilities(chromeCaps).build();Note that most calls return promises.
const el = await driver.findElement(By.name('some-elem'));const el = await driver.findElement(By.name('some-elem'));
await el.sendKeys('some text', Key.RETURN);const el = await driver.findElement(By.xpath("//*[contains(text(), 'some text')]"));...
el.click();const el = await driver.findElement(By.xpath("//input[@placeholder='some placeholder']"));const val = await el.getAttribute('some_attr');const el = await driver.findElement(By.xpath("//*[contains(text(), 'something')]"));
const parentEl = await el.findElement(By.xpath("./.."));const title = await driver.getTitle();Wait with a timeout of 2 seconds:
await driver.wait(until.titleIs('Some Title'), 2000);await driver.wait(until.elementLocated(By.xpath("//*[@placeholder='some value']")));await driver.wait(async () => {
const val = await el.getAttribute('value');
return val.match(/^some pattern/);
}, 2000);Enumerate windows and switch to the last one (assumes a single starting window with a second window just opened):
const wins = await driver.getAllWindowHandles();
await driver.switchTo().window(wins[wins.length - 1]);const jsAlert = await driver.switchTo().alert();
jsAlert.accept();