Checking an element's presence

The Selenium WebDriver does not implement Selenium RC's isElementPresent() method to check if an element is present on a page. This method is useful for building a reliable test that checks an element's presence before performing any action on it.

In this recipe, we will write a method similar to the isElementPresent() method.

How to do it...

To implement the isElementPresent() method, follow these steps:

  1. Create a method isElementPresent() and keep it accessible to your tests, shown as follows:
    private boolean isElementPresent(By by) {
      try {
        driver.findElement(by);
          return true;
        } catch (NoSuchElementException e) {
          return false;
      }
    }
  2. Now, implement a test that calls the isElementPresent() method. It will check if the desired ...

Get Selenium Testing Tools Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.