How to check if an element exist with web driver?
Is using a try catch really the only possible way?
boolean present; try { driver.findElement(By.id("logoutLink")); present = true; } catch (NoSuchElementException e) { present = false; }
You could alternatively do:
driver.findElements( By.id("...") ).size() != 0
Which saves the nasty try/catch
p.s.
Or more precisely by @JanHrcek here
!driver.findElements(By.id("...")).isEmpty()
I agree with Mike's answer but there's an implicit 3 second wait if no elements are found which can be switched on/off which is useful if you're performing this action a lot:
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS); boolean exists = driver.findElements( By.id("...") ).size() != 0 driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
Putting that into a utility method should improve performance if you're running a lot of tests
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With