KenBone KenBone - 4 months ago 21
Java Question

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

I want to use Selenium WebDriver's

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){
System.out.println("Element is Present");
System.out.println("Element is Absent");

What am I doing wrong?

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


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;