Selenium with Javascript – Locators

What is Locators

We have seen in our previous sesssions, that how can we launch a web browser and how can we navigate to a web application in a web browser, but now, if we want to know that how can we access a particular element like a button, field, text area, checkbox, then we need to use locators. So, Locators are used for locating an element in a web application.

So, Locators are an integral part of Web Automation. If we want to find an element and take action on that, then we need to use locators. Like if we want to click on a buttton, then we need to use locators, if we want to enter any value in a field or in text area, then we need to use locators.

Type of Locators

There are different type of locators which we can use to find elements in web application in a web browser in selenium webdriver.

  1. id
  2. name
  3. className
  4. tagName
  5. linkText
  6. partialLinkText
  7. cssSelector
  8. xpath

All these locators are nothing but the attributes of a particular element on the web application

How to find locator

There are some steps to find locator for a particular element.

  1. Navigate to the application in a browser
  2. Navigate to a specific page.
  3. Right click on the element and click on inspect

This way, we can find the attributes of the element and those attributes help us in finding the locator of the element.

By library

We need to import By library in our test automation script when we want to use any of the locator in order to access the element on a web application. Let’s see how to do that.

const {Builder, Browser, By, Key, until} = require('selenium-webdriver');

(async function example() {

//launch the browser
  let driver = await new Builder().forBrowser(Browser.FIREFOX).build();
 
 //navigate to the application
    await driver.get('https://www.google.com/ncr');

//type webdriver in search field and press enter
    await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN);

//wait until the title of the page changes
    await driver.wait(until.titleIs('webdriver - Google Search'), 1000);
 
//close the browser
    await driver.quit();

})();

Summary

We have covered below topics in this session.

  1. What is Locators
  2. Type of Locators
  3. How to find locators
  4. By library
  5. How to use locators to access element

Leave a Comment