top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Relative locators in Selenium

Welcome to the world of Automated Testing in Selenium where locating the elements in a web page is one of the crucial things that can happen in order to interact with the UI.


A quick recap of locators

Locators are one of the key components of Selenium infrastructure, which help Selenium scripts to uniquely identify the HTML elements in a web page.


Selenium offers different ways to find an element using locators


xpath - Locates web elements matching an XPath expression


class name - Locates a web element using their class name.


id - Locates web elements using the unique "id" attribute


name - Locates web elements using the "name" attribute


link text - Locates hyperlinks in webpage using an exact match of their link text


partial link text - Locates hyperlinks in a webpage using a partial match of their link text

tag name - Locates elements using "tag name" attribute


Why do we need relative locators?


All the above locators mentioned are traditional locators and they are pretty straightforward.

But in real time the web page and its elements may not behave as expected and we as a tester might have to locate an element using their position or visual placement on a webpage.


Relative locators act as a complement to the traditional locators. They bring a new functionality by helping you locate the web elements that are near other easily identifiable web elements.


Selenium offers 5 Relative locators


above - element to be located appears above the specified element


below - element to be located appears below the specified element


toLeftOfWeb - element to be located appears to the left of the specified element


toRightOfWeb - element to be located appears to the right of the specified element


near - element to be located is at the most 50 pixels away from the specified element.


Let's see each of these with an example. I'm accessing https://www.numpyninja.com/contact to demonstrate this.


In the below code, I have used relative locators to access all the elements in the web page. In order to use the relative location you have to import org.openqa.selenium.support.locators.RelativeLocator.


Here in all these examples, I'm able to locate the web elements based on their position with respect to other web elements.




Thank you for reading the blog. Please like it if you find it useful. Happy learning!!



48 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page