isElementPresent in Selenium-2.0
Recently while going through Selenium-2.0 I found out that WebDriver does not have a function called isElementPresent(). This was one of the important functions that was used in Selenium-1.0. It was mainly used for waiting for an element to be available to take an action on it. To implement this in WebDriver you just need to write a method as mentioned below. You can then use this function with any type of "By"(By.id, BY.name, etc.)
1
2
3
4
5
6
7
8
| private boolean isElementPresent(WebDriver driver, By by){ try{ driver.findElement(by); return true; }catch(NoSuchElementException e){ return false; } } |
The above function will return true in case the element is found on the page, else it will return false. For ex. The above function can be used for implementing thewaitForElementPresent function of Selenium-IDE as mentioned below.
1
2
3
4
5
6
| for (int second = 0;; second++) { if (second >= 60) fail("timeout"); try { if (this.isElementPresent(driver,By.linkText("Software testing - Wikipedia, the free encyclopedia"))) break; Thread.sleep(1000); } catch (Exception e) {} } |
Excellent explanation. This is one of those classic Selenium migration gotchas that every automation tester encounters when moving from RC to WebDriver. You’ve broken it down really well, and the custom isElementPresent() helper is still a clean, dependable solution when you don’t want to use explicit waits.
ReplyDeleteThat said, it’s also a good moment to think about modernising test reliability. Wrapping helpers like this into a framework and pairing them with robust reporting helps QA teams keep visibility across fast-moving projects. Tools like test management software Tuskr make it easy to log, review, and track automated test outcomes so your efforts in writing resilient utilities like isElementPresent directly improve your team’s overall quality metrics.