How can I check if an element exists with Selenium WebDriver?
Use the mixture of findElements()
and isEmpty()
to swiftly check for element presence in Selenium WebDriver. This avoids the need for exceptions and set up an uncomplicated boolean check.
Simple version:
This line of code will give you true
if your element is on the page, and false
if it's not.
Upgrade insights and optimization
To boost the effectiveness of the basic answer, you can incorporate the various methods for checking the existence of an element to make your tests more robust and easier to manage.
Speedy checks with implicit waits
To speed up your existence checks, you can temporarily set the implicit wait to zero. Like ordering a pizza and telling them you have all day, then calling them every two minutes to ask where your pepperoni delight is.
Multipurpose utility methods (because we hate repeating!)
Creating multipurpose utility methods can help us combat code repetition:
Extending WebDriver and WebElement because we can!
Consider extending IWebDriver
and IWebElement
to grow their potential:
Steady balance between waits and checks
A few techniques can help to play with waiting times and checking for element existence.
Shun exception handling
Steer clear of try-catch
for NoSuchElementException
because it's just too not cool for this use case, man.
Fixed stare on the loading page
Custom methods should respect the page's personal time, especially if it's a lazy loader. In such cases, explicit waits can be your new best friend:
Was this article helpful?