Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebDriver: check if an element exists? [duplicate]

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; } 
like image 204
Ralph Avatar asked Jun 29 '11 13:06

Ralph


2 Answers

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() 
like image 93
Mike Kwan Avatar answered Oct 01 '22 10:10

Mike Kwan


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

like image 39
Edd Avatar answered Oct 01 '22 11:10

Edd