KenBone KenBone - 1 month ago 5
Java Question

How to detect the presence of an element with Selenium Webdriver in Java

I want to use Selenium WebDriver's

findElement()
function to detect if an element is present on a page. No matter what I do, Selenium exits the code even if I throw the WebDriverException.

I tried using this code, but it didn't prevent Selenium from exiting:

if(driver.findElement(By.xpath(xpath) != null){
driver.findElement(By.xpath(xpath)).click();
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}


What am I doing wrong?

isDisplayed()
also seems to have a similar error. Am I just using the wrong methods or am I using the methods incorrectly?

Answer

Yes, you can use findElements. I wrote you an example below:

public WebElement element(WebDriver driver) {
    List<WebElement> list = driver.findElements(By.xpath("xpath"));
    if (list != null && !list.isEmpty()) {
        return list.get(0);
    }
    return null;
}
element.click();