How to use Selenium Web Driver and JavaScript to Login any website?


Nowadays, automation is very useful for testing the application. Many automation tools are available, and Selenium is one of them, developed in 2004. Also, it is a crossplatform tool, so we can use Selenium with most programming languages, and here we will use it with JavaScript.

Users need to create the NodeJS application to use the Selenium web driver with JavaScript.

Create a NodeJS Application

Users can follow the steps below to create a NodeJS application.

Step 1 – Open the project directory in the terminal and enter the below command.

npm init -y

Step 2 – Now, enter the below command in the project directory to install the seleniumwebdriver NPM package in the project.

npm install selenium-webdriver 

Step 3 – Users also need to install the chrome web driver to use Selenium with the chrome browser. Use the below command to install the chrome driver.

npm install chromedriver 

Step 4 – Create an app.js file and add the code to log in to any site.

Step 5 – Execute the below command to run the code of the app.js file.

node app.js 

Algorithm

Users can follow the below steps to log in to any website.

Step 1 – Import the ‘chromedriver’, and ‘selenium-webdriver’.

require("chromedriver");
let seleniumDriver = require("selenium-webdriver");

Step 2 – Open the browser window.

let seleniumBuilder = new seleniumDriver.Builder();
let browserTab = seleniumBuilder.forBrowser("chrome").build(); 

Step 3 – Open the URL in the browser tab.

let browserWindow = browserTab.get("URL"); 

Step 4 – Resolve the promises. Find the username input field using the CSS selector. To find the CSS selector, users should go respected webpage. For example, in our case, go to the ‘https://practicetestautomation.com/practice-test-login/’ webpage.

Users will see the interface below.

After that, right-click on the username input field. It will show a menu, and users need to select the last option named ‘inspect’ in the menu.

It will open up the chrome developer tool. In this, users need to find the element and get its id or class name.

In our case, we will use the id of the username input field as a CSS selector. Here, the id of the username field is ‘username’.

let userInputBox = browserTab.findElement(
   seleniumDriver.By.css("#username")
);

Step 5 – Send the username to the user input box as a key.

let sendUserName = userNameInput.sendKeys("student"); 

Step 6 – Find the password input field using the CSS selector, and send the password as a key, like a username.

Step 7 – Find the sign-in button, and click the button using the click() button.

continueBtn.click(); 

Step 8 – Sign in using Selenium is successful.

Example

In the example below, we followed the steps above to log in to the ‘https://practicetestautomation.com/practice-test-login/’ website using the Selenium webdriver. First, we set the timeout for 5 seconds using the setTimeOut() function to overcome the slow connection.

After that, we used the promise chaining to get the username, send keys to the username, get password input, send keys to the password, find the login button, and click the login button.

// import chrome driver
require("chromedriver");

// import selenium webdriver
let seleniumDriver = require("selenium-webdriver");

// get the browser instance
let seleniumBuilder = new seleniumDriver.Builder();
let browserTab = seleniumBuilder.forBrowser("chrome").build();

// open the browser
let browserWindow =
browserTab.get("https://practicetestautomation.com/practice-testlogin/");

// resolve promises
browserWindow
   .then(function () {
      
      // set timeout for connection delay
      let timeOut = browserTab.manage().setTimeouts({
         implicit: 5000,
      });
      return timeOut;
   })
   .then(() => {
      
      // get a user input box
      let userInputBox = browserTab.findElement(
         seleniumDriver.By.css("#username")
      );
      return userInputBox;
   })
   .then((userNameInput) => {
      
      // send username keys
      let sendUserName = userNameInput.sendKeys("student");
      return sendUserName;
   })
   .then(() => {
      console.log("Username filled!");
      
      // get a password input box
      let userPasswordBox = browserTab.findElement(
         seleniumDriver.By.css("#password")
      );
      return userPasswordBox;
   })
   .then((passwordInput) => {
      
      // send password keys
      let sendPasswords = passwordInput.sendKeys("Password123");
      return sendPasswords;
   })
   .then(() => {
      console.log("Password filled!");
      
      // get the continue button
      let continueButton = browserTab.findElement( 
         seleniumDriver.By.css("#submit")
      );
      return continueButton;
   })
   .then((continueBtn) => {
      
      // click on the continue button
      continueBtn.click();
      console.log("SignIN completed!");
   })
   .catch(function (error) {
      console.log("Error ", error);
   });

Output

In the above output, users can observe that first, it opens a browser window, then it opens the URL, fills the credentials to the input and clicks the submit button.

Users can observe the below messages in the console.

Example

In the example below, we used the selenium web driver to automate the login ‘https://dev.to/enter’ website. We have found the username field using the ‘user_email’ id and the password field using the ‘user_password’ field.

Users need to ensure they have an account on the ‘dev.to’ website. While testing the code below, ensure you replace <your_username> with your email and <your_password> with your password.

require("chromedriver");
let seleniumDriver = require("selenium-webdriver");
let seleniumBuilder = new seleniumDriver.Builder();
let browserTab = seleniumBuilder.forBrowser("chrome").build();
let browserWindow = browserTab.get("https://dev.to/enter");
browserWindow
   .then(function () {
      let timeOut = browserTab.manage().setTimeouts({
         implicit: 5000,
      });
      return timeOut;
   })
   .then(() => {
      let userInputBox = browserTab.findElement(
         seleniumDriver.By.css("#user_email") 
      );
      return userInputBox;
   })
   .then((userNameInput) => {
      let sendUserName = userNameInput.sendKeys("<Your_username>");
      return sendUserName;
   })
   .then(() => {
      console.log("Username filled!");
      let userPasswordBox = browserTab.findElement(
         seleniumDriver.By.css("#user_password")
      );
      return userPasswordBox;
   })
   .then((passwordInput) => {
      let sendPasswords = passwordInput.sendKeys("<Your_password>");
      return sendPasswords;
   })
   .then(() => {
      console.log("Password filled!");
      
      // get the continue button
      let continueButton = browserTab.findElement(
         seleniumDriver.By.css(".crayons-btn.crayons-btn--l")
      );
      return continueButton;
   })
   .then((continueBtn) => {
      
      // click on the continue button
         continueBtn.click();
         console.log("SignIN completed!");
      })
      .catch(function (error) {
         console.log("Error ", error);
      });

Output

This tutorial taught us to log in to two websites using the Selenium web driver. The Selenium web driver is very useful for testing for automation, and also, it is used to scrap data from different websites.

For login automation, users need to find the input fields by CSS selector and need to send keys using the selenium webdriver. At last, users need to click the sign-in button using the click() method. If users want to use the selenium webdriver with firefox, they should install the firefox driver instead of the chrome driver.

Updated on: 07-Mar-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements