How to use selenium-webdriver

Comprehensive selenium-webdriver code examples:

How to use selenium-webdriver.prototype:

23
24
25
26
27
28
29
30
31
32
  engines.selenium.registerCommand(commands.REQUESTS_STOP, 'DELETE', '/session/:sessionId/autotester/requests');
  engines.selenium.registerCommand(commands.REQUESTS_GET, 'POST', '/session/:sessionId/autotester/requests');
}

function addRequestsMethod() {
  WebDriver.prototype.requests = function () {
    if (!this.collector_) {
      this.collector_ = new Collector(this);
    }
    return this.collector_;

How to use selenium-webdriver.writeFileSync:

200
201
202
203
204
205
206
207
208
```

Example:

```
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();
```

#### Using WebDriverIO

How to use selenium-webdriver.Options:

1
2
3
4
5
6
7
8
9
10
const { ServiceBuilder } = require('selenium-webdriver/firefox');
async function createDriver (url)
{
    let driver = await new Builder().forBrowser(Browser.FIREFOX).build();
    const serviceBuilder = new ServiceBuilder("");
/*     const options = new Options(driver);
    options.binary_location = '/var/lib/flatpak/app/org.mozilla.firefox/x86_64/stable/9c4d1797620e52ab380ffcbbff9a947ccb39695a8ca14e44935d9578d5c88b6d/files/lib/firefox/';
     */
    await driver.get(url);
    return driver;

How to use selenium-webdriver.ChromeOptions:

142
143
144
145
146
147
148
149
150
151
from selenium import webdriver
#Replace the version to match the Chrome version
import selenium.webdriver.common.devtools.v93 as devtools

async def geoLocationTest():
    chrome_options = webdriver.ChromeOptions()
    driver = webdriver.Remote(
        command_executor='<grid-url>',
        options=chrome_options
    )

How to use selenium-webdriver.Remote:

143
144
145
146
147
148
149
150
151
#Replace the version to match the Chrome version
import selenium.webdriver.common.devtools.v93 as devtools

async def geoLocationTest():
    chrome_options = webdriver.ChromeOptions()
    driver = webdriver.Remote(
        command_executor='<grid-url>',
        options=chrome_options
    )

How to use selenium-webdriver.Level:

How to use selenium-webdriver.Chrome:

42
43
44
45
46
47
48
49
50
51
  {{< tab header="Python" >}}
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

def geoLocationTest():
    driver = webdriver.Chrome()
    Map_coordinates = dict({
        "latitude": 41.8781,
        "longitude": -87.6298,
        "accuracy": 100

How to use selenium-webdriver.WebElementCondition:

34
35
36
37
38
39
40
41
42

/* eslint-disable no-unused-vars */
function waitForVisibleElement (locator, t) {
  var timeout = t || 3000;
  var element = driver.wait(until.elementLocated(locator), timeout);
  return driver.wait(new webdriver.WebElementCondition('for element to be visible ' + locator, function () {
    return element.isDisplayed().then(x => x ? element : null);
  }), timeout);
}

How to use selenium-webdriver.Capability:

13
14
15
16
17
18
19
20
21
22
this.ActionSequence = webdriver.ActionSequence;
this.Browser = webdriver.Browser;
this.Builder = webdriver.Builder;
this.Button = webdriver.Button;
this.Capabilities = webdriver.Capabilities;
this.Capability = webdriver.Capability;
this.EventEmitter = webdriver.EventEmitter;
this.FileDetector = webdriver.FileDetector;
this.Key = webdriver.Key;
this.Session = webdriver.Session;

How to use selenium-webdriver.Button:

11
12
13
14
15
16
17
18
19
20
this.ProtractorExpectedConditions = require('./expectedConditions').ProtractorExpectedConditions;
// Export selenium webdriver.
this.ActionSequence = webdriver.ActionSequence;
this.Browser = webdriver.Browser;
this.Builder = webdriver.Builder;
this.Button = webdriver.Button;
this.Capabilities = webdriver.Capabilities;
this.Capability = webdriver.Capability;
this.EventEmitter = webdriver.EventEmitter;
this.FileDetector = webdriver.FileDetector;

How to use selenium-webdriver.Session:

17
18
19
20
21
22
23
24
25
26
this.Capabilities = webdriver.Capabilities;
this.Capability = webdriver.Capability;
this.EventEmitter = webdriver.EventEmitter;
this.FileDetector = webdriver.FileDetector;
this.Key = webdriver.Key;
this.Session = webdriver.Session;
this.WebDriver = webdriver.WebDriver;
this.WebElement = webdriver.WebElement;
this.WebElementPromise = webdriver.WebElementPromise;
this.error = webdriver.error;

How to use selenium-webdriver.FileDetector:

15
16
17
18
19
20
21
22
23
24
this.Builder = webdriver.Builder;
this.Button = webdriver.Button;
this.Capabilities = webdriver.Capabilities;
this.Capability = webdriver.Capability;
this.EventEmitter = webdriver.EventEmitter;
this.FileDetector = webdriver.FileDetector;
this.Key = webdriver.Key;
this.Session = webdriver.Session;
this.WebDriver = webdriver.WebDriver;
this.WebElement = webdriver.WebElement;

How to use selenium-webdriver.ActionSequence:

8
9
10
11
12
13
14
15
16
17
this.ElementFinder = require('./element').ElementFinder;
this.ElementArrayFinder = require('./element').ElementArrayFinder;
this.ProtractorBy = require('./locators').ProtractorBy;
this.ProtractorExpectedConditions = require('./expectedConditions').ProtractorExpectedConditions;
// Export selenium webdriver.
this.ActionSequence = webdriver.ActionSequence;
this.Browser = webdriver.Browser;
this.Builder = webdriver.Builder;
this.Button = webdriver.Button;
this.Capabilities = webdriver.Capabilities;

How to use selenium-webdriver.EventEmitter:

14
15
16
17
18
19
20
21
22
23
this.Browser = webdriver.Browser;
this.Builder = webdriver.Builder;
this.Button = webdriver.Button;
this.Capabilities = webdriver.Capabilities;
this.Capability = webdriver.Capability;
this.EventEmitter = webdriver.EventEmitter;
this.FileDetector = webdriver.FileDetector;
this.Key = webdriver.Key;
this.Session = webdriver.Session;
this.WebDriver = webdriver.WebDriver;

How to use selenium-webdriver.Condition:

78
79
80
81
82
83
84
85
86
87
    driver => this.findOne(scope || driver).catch(() => null)
  );
};

Query.prototype.untilSome = function (scope) {
  return new webdriver.Condition(`for ${this}`,
    driver => this.findAll(scope || driver).then(
      list => (list && list.length ? list : null)
    )
  );

How to use selenium-webdriver.Browser:

210
211
212
213
214
215
216
217
218
219
end

  {{< /tab >}}
  {{< tab header="JavaScript" >}}
const webdriver = require('selenium-webdriver');
const BROWSER_NAME = webdriver.Browser.CHROME;

async function getDriver() {
  return new webdriver.Builder()
  .usingServer('<grid-url>')

How to use selenium-webdriver.error:

6
7
8
9
10
11
12
13
14

//simplify webdriver usage
global.by = webdriver.By;
global.key = webdriver.Key;
global.promise = webdriver.promise;
global.bot = webdriver.error;
global.until = webdriver.until;

module.exports = fiveby;

How to use selenium-webdriver.WebDriver:

18
19
20
21
22
23
24
25
26
27
this.Capability = webdriver.Capability;
this.EventEmitter = webdriver.EventEmitter;
this.FileDetector = webdriver.FileDetector;
this.Key = webdriver.Key;
this.Session = webdriver.Session;
this.WebDriver = webdriver.WebDriver;
this.WebElement = webdriver.WebElement;
this.WebElementPromise = webdriver.WebElementPromise;
this.error = webdriver.error;
this.logging = webdriver.logging;

How to use selenium-webdriver.css:

75
76
77
78
79
80
81
82
83
        });
    })
]);

// Submit login button
driver.findElement( By.css('#submit_login') )
  .then(function(el){
    el.click();
  });

How to use selenium-webdriver.WebElementPromise:

51
52
53
54
55
56
57
58
59
60
  const fwd = scope.driver_ || scope;
  const el = this.filters
    ? this.all(scope).then(matches => this.assert(matches[0]))
    : scope.findElement(this.by).catch(() => this.assert());

  const elementPromise = new webdriver.WebElementPromise(fwd, el);
  return fwd._decorateElement(elementPromise);
};

Query.prototype.findAll = function (scope) {

How to use selenium-webdriver.WebElement:

How to use selenium-webdriver.until:

9
10
11
12
13
14
15
16
17
18
const promise = require('selenium-webdriver/lib/promise')
const chromedriver = require('chromedriver')
const log = require('npmlog')

// shortcuts
const until = webdriver.until
const By = webdriver.By

/* -----------------------------------------------------------------------------
 * configure

How to use selenium-webdriver.Key:

6
7
8
9
10
11
12
13
14
15
    ...capabilities['browser'] && { browserName: capabilities['browser']}  // Because NodeJS language binding requires browserName to be defined
  })
  .build();
await driver.get("http://www.google.com");
const inputField = await driver.findElement(webdriver.By.name("q"));
await inputField.sendKeys("BrowserStack", webdriver.Key.ENTER); // this submits on desktop browsers
try {
  await driver.wait(webdriver.until.titleMatches(/BrowserStack/i), 5000);
} catch (e) {
  await inputField.submit(); // this helps in mobile browsers

How to use selenium-webdriver.promise:

0
1
2
3
4
5
6
7
8
9
const webdriver = require('selenium-webdriver');
const async = require('async');


function driversetup(nemo) {
  var d = webdriver.promise.defer();
  async.waterfall([function setup(cb) {
    nemo.driver = new webdriver
      .Builder()
      .forBrowser('phantomjs')

How to use selenium-webdriver.logging:

128
129
130
131
132
133
134
135
136
137
  });
}

// Provide the webdriver driver and type of logging:
// https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/logging_exports_Type.html
// Browser console logs: webdriver.logging.Type.BROWSER
// WebDriver driver logs: webdriver.logging.Type.DRIVER
function getLogs(driver, type) {
  // https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_Logs.html
  driver.manage().logs().get(type)

How to use selenium-webdriver.By:

56
57
58
59
60
61
62
63
64
65
return function() {
  driver.get(`http://localhost:10114/dist/${url}`);
  return new Promise(function(resolve, reject) {
    driver
      .wait(function() {
        var readyroot = webdriver.By.css('html.ts-ready'); // not needed?
        return driver.findElements(readyroot);
      })
      .then(function() {
        currenturl = url;

How to use selenium-webdriver.Capabilities:

32
33
34
35
36
37
38
39
40
41
 * 127.0.0.1    firstparty.local
 * 127.0.0.1    thirdparty.local
 */

async function loadDriverWithExtension(extPath) {
  let chromeOptions = sw.Capabilities.chrome();
  chromeOptions.set("chromeOptions",  {"args": [
    `--load-extension=${extPath}`,
    '--no-sandbox',
  ]});

How to use selenium-webdriver.Builder:

213
214
215
216
217
218
219
220
221
  {{< tab header="JavaScript" >}}
const webdriver = require('selenium-webdriver');
const BROWSER_NAME = webdriver.Browser.CHROME;

async function getDriver() {
  return new webdriver.Builder()
  .usingServer('<grid-url>')
  .forBrowser(BROWSER_NAME)
  .build();