Relative Locators in Selenium (Selenium 4 Features)



Relative Locators 

  • Till now we have used many locators like Xpath, Css, Id, Name, Link etc. in total so far we have 8 locators, however with selenium 4, we will be using few more locators.


  • Selenium 4 provide us a new way to find the WebElement or i would say (Near by WebElement) based on the other Element present in the DOM


  • Selenium 4 provide the functionality of "Relative Locators" This functionality is added to help us locate elements that are nearby other elements. The Available Relative Locators are:
    • above
    • below
    • toLeftOf
    • toRightOf
    • near

Syntax 

driver.findElement(withTagName("Element to find").below(By.xpath("Element present in DOM"))).sendKeys("Selenium");

Explanation:-


  • FindElement method now accepts a new method "withTagName".
  • "withTagName" function accept the tag Name of a webElement which we are trying to find to perform further actions as sendKeys().
  • .below is the Relative Locator which internally use JavaScript function getBoundingClientRect() to find the relative elements.
  • Below Locator takes the input argument as a webElement.

Sample Code 

package Demo.Selenium4updates;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Selenium4RelativeXpath2rediff {
public static WebDriver driver ;
@Test
public static void test() 
{
try {
WebDriverManager.chromedriver().setup();
driver= new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://register.rediff.com/register/register.php?FormName=user_details");
Thread.sleep(3000);
driver.findElement(withTagName("input").below(By.xpath("//*[@id='tblcrtac']/tbody/tr[3]/td[3]/input"))).sendKeys("tgerst");
}
catch(Exception e )
{
e.printStackTrace();
System.out.println("Getting error");
}
}

    • Using  above code we are sending inputs to Rediff ID,  Please have a look to below screen.




    Post a Comment