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.
To implement the isElementPresent()
method, follow these steps:
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; } }
isElementPresent()
method. It will check if the desired element is present on a page. If found, it will click on the element; else it fails the test. This is done as follows:@Test public void testIsElementPresent() { // Check if element with locator criteria exists on Page if (isElementPresent(By.name("airbags"))) { // Get the checkbox and select it WebElement airbag = driver.findElement(By.name("airbags")); if (!airbag.isSelected()) { airbag.click(); } } else { fail("Airbag Checkbox doesn't exists!!"); } }
The isElementPresent()
method takes a locator using an instance of By
. It then calls the findElement()
method. If the element is not found, a NoSuchElementException
exception will be thrown. Using the try and catch block, the isElementPresent()
method will return true if the element is found and no exception is thrown; otherwise, it will return false if NoSuchElementException
is thrown by the findElement()
method.
18.227.72.15