Loading...
Each browser has a native support for automation. WebDriver use this automation to provide concise API for interacting with a browser. In this tutorial we will try to use JavaScript and WebDriver to interact programmically with our browser.
let's start by creating a new project. Create a new folder called webdriver-tutorial cd into that folder and init npm in that folder by typing:
> npm init --yes
install webdriver with npm with the following command
> npm install selenium-webdriver@3.6.0
Depending on the browser we want to launch, we will need to install the proper driver for that browser. For this tutorial we will use Chrome as our browser, so install the chromedriver using npm
> npm install chromedriver
Let's try and use that package to interact with our browser. Create a new file called webdriver-tutorial.js place the following code in that file.
const { Builder } = require('selenium-webdriver');
let driver = new Builder()
.forBrowser('chrome')
.build();
Try and launch the file by typing
> node webdriver-tutorial.js
You should see the browser popping up. Now that we have the chrome webdriver, we can use it to interact with the browser. Let's fetch a certain page. place the following code at the end of the file webdriver-tutorial.js
driver.get("https://www.bugeez.io");
the browser should launch and go to the url you typed. what we are doing is creating a webdriver for chrome and using it to get a certain url.
using the browser we can also interact with the browser by grabbing an element, clicking a button, filling forms, etc. Let's try to interact with the bugeez page and activate the hamburger menu and click the link to the login page. At the bottom of the file add the following:
const { Builder, By } = require('selenium-webdriver');
let driver = new Builder()
.forBrowser('chrome')
.build();
async function gotoLogin() {
await driver.get("https://www.bugeez.io");
await driver.findElement(By.css('.trigger-sidebar-nav')).click();
await new Promise(resolve => setTimeout(resolve, 1000));
await driver.findElement(By.css('.main-side-menu-inner ul li:nth-of-type(5)')).click();
}
gotoLogin();
Let's go over what is happening here.
This is just the tip of the iceberg with what we can do we selenium-webdriver. Try and automate your repeating tasks and play with more complex examples.