Selenium Check if Element Exists

Profile picture for user arilio666

In selenium, we can check whether an element exists on a page using the findElement() and isDisplayed() methods. This article will discuss how we can check whether the element is visible using the above.

  • We will use the programsbuzz login page to enter incorrect credentials and then check whether the error message appears or not after the wrong inputs.
public static void main(String[] args) throws InterruptedException {
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://programsbuzz.com/user/login");
        driver.manage().window().maximize();
        driver.findElement(By.id("edit-name")).sendKeys("gg");
        driver.findElement(By.id("edit-pass")).sendKeys("mm");
        driver.findElement(By.xpath("//input[@value='Log in']")).click();
        Thread.sleep(4000);
        boolean errorMessage = driver.findElement(By.xpath("//div[@class='messages messages--error']")).isDisplayed();
        if (errorMessage) {
            System.out.println("Incorrect Credentials");
        } else {
            System.out.println("No Error Message");
        }
    }
}
  • Here we entered an incorrect username and password for login.
  • As soon as the error message popped, we grabbed the element and assigned isDisplayed() to it.
  • Using a simple if statement, we ensured that the error message is displayed and the element thus exists and is verified.