Automation QA Testing Course Content

Selenium 4 - Relative Locators

 

Relative Locators

  • Relative locators.
  • Writing and building codes to maintain locators has been a common practice of all test engineers. This practice is quite time-consuming and challenging. 
  • Tools like Sahi and Taiko have features to locate the nearby elements by specifying the directions, however, to accomplish the same in the selenium we need to deal with the complicated xpaths and CSS locators which might result in brittle or flaky test cases.
  • The relative locators in selenium 4 provide a better solution by helping us to locate the elements based on their positions with respect to other elements. 
  • Relative locators provide a newly added locator strategy to the existing eight locator strategies.(id, name, XPath, cssSelector, linkText, partial LinkText, className, and tagName). Relative locators locate the element with respect to the nearby specified elements.
  • A new method withTagName() is added, which returns an instance of RelativeLocator.RelativeBy class, a child class of By and offers methods to specify the direction of an element to be located.
    • above(): Used to locate an element just above the specified element
    • below(): Used to locate an element just below the specified element
    • toLeftOf(): Used to locate an element located on the left side of a specified element
    • toRightOf(): Used to locate an element located on the right side of a specified element
    • near(): By default, it is used to locate an element at 50 pixels distant from a specified element. 

These five relative locators, when added to the existing eight locator strategies, help to get more accurate results for locating the elements, eventually saving from creating flaky test cases.

Note: Method “withTagName()” is added which returns an instance of RelativeLocator. Above relative locators support this method “withTagName()


//Assume element1 is above element2

WebElement element1;

element1 = driver.findElement(By.id("1234"));

String element2 = driver.findElement(withTagName("ABC").below(element1)).getText();

System.out.println("Element below element1 is "+ element2);


//Assume element0 is above element1

WebElement element1;

element1 = driver.findElement(By.id("1234"));

String element0 = driver.findElement(withTagName("ABC").above(element1)).getText();

System.out.println("Element above element1 is "+ element0);



//Assume element1 is on the left side of element3

WebElement element1;

element1 = driver.findElement( withTagName("ABC").toLeftOf(element3)).getText();

System.out.println(" Left of element 3 is : "+ element1);



//Assume element3 is on the right side of element1

WebElement element3;

element3 = driver.findElement( withTagName("ABC").toRightOf(element1)).getText();

System.out.println(" Right of element 1 is : "+ element3);


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.