Locate WebElement in Selenium with Multiple Locators - Bug Reaper

                  Bug Reaper

Lean about Automation Testing,Selenium WebDriver,RestAssured,Appium,Jenkins,JAVA,API Automation,TestNG,Maven, Rest API, SOAP API,Linux,Maven,Security Testing,Interview Questions

Friday, 20 April 2018

Locate WebElement in Selenium with Multiple Locators

Locate WebElement in Selenium with Multiple Locators

Problem:
Sometimes WebElement are so dynamic in application that we can't always rely on Single Locator for WebElement in such we can use following approach

Solution: We can use pipe (|) and we can combine multiple Xpath

driver.findElement(By.xpath("Locator 1| Locator 2|Locator 3");


Now selenium will try to find Element with all three locators


In my case
Correct Locator:
(//input[@class='search-field'])[2]

Incorrect Locator:
(//input[@class='searchfield'])[2]

Incorrect Locator: html/section/div[2]/div[1]/form

Sample below Code
 package com.neeraj.test.neeraj;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Selenium {  
      public static void main(String[] args) {  
           WebDriver driver=new FirefoxDriver();  
           driver.get("http://time.com/");  
           WebElement element=driver.findElement(By.xpath("html/body/header/nav[1]/section/section/div[2]/div[9]/button"));  
           element.click();  
           element=driver.findElement(By.xpath("html/section/div[2]/div[1]/form|(//input[@class='searchfield'])[2]|(//input[@class='search-field'])[2]"));  
           element.click();  
           element.sendKeys("rolex");  
           driver.close();  
      }  
 }  

No comments:

Post a Comment