Tips and tricks

In this section, we will take a look at some tips and tricks that might be of use when trying to find elements on the page. We can also apply them to see whether the elements are not on the page.

Finding if an element exists without throwing an error

Selenium WebDriver is really good at letting you know when an element does not exist. If it throws NoSuchElementException, then we know it's not there. Unfortunately, I, and many others, are not big fans of using exception handling as a means of flow control.

To get around this, we can use the findElements() call, and then we just need to check that the size of the list returned is 0. For example:

List<WebElement> elements = driver.findElements(By.Id("myElement")); elements.size(); //This ...

Get Learning Selenium Testing Tools - Third 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.