How to select an element when either of the elements can be found using Selenium and Java How to select an element when either of the elements can be found using Selenium and Java selenium selenium

How to select an element when either of the elements can be found using Selenium and Java


You can use findElements() instead of findElement(), that would return a list of web element.

Now, if the size is 1, your script will get to know that particular element is present. If the size id 0, then button will not be visible in UI.

Something like this for quantity button :

List<WebElement> quantityButton = driver.findElements(By.xpath("//select[@id='quantity']"));if(quantityButton.size()==1){   quantityButton.get(0).click();}  

For amt Button :

List<WebElement> amtButton = driver.findElements(By.xpath("//select[@id='amt']"));    if(amtButton.size()==1){       amtButton.get(0).click();    }  

You can write respective else block as per your requirement.

Different approach would be to go with try-catch block.

Let me know if that helps.


As cruisepandey already provided logic how to handle this kind of scenario.For all your confusion you can try nested if..else loop where it will check the first element size() if it comes 0 if will go inside another loop and check the second element size().

if(driver.findElements(By.xpath("//select[@id='quantity']")).size()==0){ if(driver.findElements(By.xpath("//select[@id='amt']")).size()>0) {   driver.findElements(By.xpath("//select[@id='amt']")).get(0).click();    Select amt = new Select(driver.findElement(By.xpath("//select[@id='amt']")));   amt.selectByIndex(1);  } else {   System.out.println("None of the elements present") }}else{  driver.findElements(By.xpath("//select[@id='quantity']")).get(0).click();  Select quantity = new Select(driver.findElement(By.xpath("//select[@id='quantity']")));  quantity.selectByIndex(1); }       


As you mentioned either one element is found presumably the element is a dynamic element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • Using xpath:

    WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.or(    ExpectedConditions.visibilityOfElementLocated(By.xpath("//select[@id='quantity']")),    ExpectedConditions.visibilityOfElementLocated(By.xpath("//select[@id='amt']"))));Select amt = new Select(element);quantity.selectByIndex(1); 
  • Using cssSelector:

    WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.or(    ExpectedConditions.visibilityOfElementLocated(By.cssSelector("select#quantity")),    ExpectedConditions.visibilityOfElementLocated(By.cssSelector("select#amt"))));Select quantity = new Select(element);quantity.selectByIndex(1);