1

I am trying to find an element using xpath.

I tried this method:

    if(a_chromeWebdriver.findElement(By.xpath(XPATH1)) != null){
        homeTable = a_chromeWebdriver.findElement(By.xpath(XPATH1));
    }
    else{
        homeTable = a_chromeWebdriver.findElement(By.xpath(XPATH2));
    }

I assumed that if the first xpath won't be found, it will try he second one. But it throws an exception of element not found.

I also tried to check size = 0 instead of null, but got the same result.

4 Answers 4

3

You can use this method to check whether your xpath is present or not :

create a method : isElementPresent

public boolean isElementPresent(By by) {
    try {
      driver.findElements(by);
      return true;
    } catch (org.openqa.selenium.NoSuchElementException e) {
      return false;
    }
}

Call it using xpath like this :

 isElementPresent(By.xpath(XPATH1));

So your code would become :

if(isElementPresent(By.xpath(XPATH1))){
        homeTable = a_chromeWebdriver.findElement(By.xpath(XPATH1));
    }
    else{
        homeTable = a_chromeWebdriver.findElement(By.xpath(XPATH2));
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You could use findElements instead of findElement and then check the size:

List<WebElement> elements = a_chromeWebdriver.findElements(By.xpath(XPATH1));
if(elements.size() > 0){
    homeTable = elements.get(0);
} else{
    homeTable = a_chromeWebdriver.findElement(By.xpath(XPATH2));
}

But a better way would be to combine the 2 XPath in a single one with |:

homeTable = a_chromeWebdriver.findElement(By.xpath(XPATH1 + "|" + XPATH2));

Comments

0

You could create a method,

public WebElement getElement(By by) {
    try { 
        return a_chromeWebdriver.findElement(by);
    } catch (org.openqa.selenium.NoSuchElementException e) {
        return null;
    }
}

You could use it as follows,

WebElement element = getElement(By.xpath(XPATH1));
if (element == null)
    element = getElement(By.xpath(XPATH2));

Comments

0
  1. First add implicit wait to your code that will handle synchronization issues driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

  2. Add OR Operator rather than adding condition as other answers points out. homeTable = a_chromeWebdriver.findElement(By.xpath(XPATH1 | XPATH2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.