WebDriver: check if element exists?

How to check if element exists with web driver?

Is using try catch really the only way possible?

boolean present; try { driver.findElement(By.id("logoutLink")); present = true; } catch (NoSuchElementException e) { present = false; } 
+86
java testing selenium-webdriver webdriver
Jun 29 '11 at 13:17
source share
10 answers

You can also do:

 driver.findElements( By.id("...") ).size() != 0 

What keeps the unpleasant try / catch

+164
Jun 29 '11 at 13:57
source share

I agree with Mike's answer, but there is an implicit 3-second wait if no items are found that can be turned on / off, which is useful if you do this a lot:

 driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS); boolean exists = driver.findElements( By.id("...") ).size() != 0 driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); 

Enabling this utility method should improve performance if you run many tests.

+38
Jan 09 2018-12-12T00:
source share

As the comment says, this is in C #, not Java, but the idea is the same. I have investigated this problem extensively, and the final problem is that FindElement always returns an exception when an element does not exist. There is no overloaded option that allows you to get zero or something else. That is why I prefer this decision over others.

  • Returns a list of items, and then checks to see if the size of the list is 0, but you are losing functionality. You cannot do .click () in a collection of links, even if the size of the collection is 1.
  • You can claim that an element exists, but often this stops your testing. In some cases, I have an additional click link, depending on how I got to this page, and I want to click it if it exists, or go otherwise.
  • This will only be slow unless you set the driver.Manage () timeout . Timeouts (). ImplicitlyWait (TimeSpan.FromSeconds (0));
  • In fact, it is very simple and elegant after creating the method. Using FindElementSafe instead of FindElement , I don't see the “ugly try / catch block”, and I can use the simple Exists method. It will look something like this:

     IWebElement myLink = driver.FindElementSafe(By.Id("myId")); if (myLink.Exists) { myLink.Click(); } 

This is how you extend IWebElement and IWebDriver

IWebDriver.FindElementSafe

  /// <summary> /// Same as FindElement only returns null when not found instead of an exception. /// </summary> /// <param name="driver">current browser instance</param> /// <param name="by">The search string for finding element</param> /// <returns>Returns element or null if not found</returns> public static IWebElement FindElementSafe(this IWebDriver driver, By by) { try { return driver.FindElement(by); } catch (NoSuchElementException) { return null; } } 

IWebElement.Exists

  /// <summary> /// Requires finding element by FindElementSafe(By). /// Returns T/F depending on if element is defined or null. /// </summary> /// <param name="element">Current element</param> /// <returns>Returns T/F depending on if element is defined or null.</returns> public static bool Exists(this IWebElement element) { if (element == null) { return false; } return true; } 

You can use polymorphism to modify an instance of the IWebDriver class of the FindElement class, but this is a bad idea in terms of maintenance.

+5
Aug 05 '13 at 15:06
source share

you can make a statement.

see example

 driver.asserts().assertElementFound("Page was not loaded", By.xpath("//div[@id='actionsContainer']"),Constants.LOOKUP_TIMEOUT); 

you can use this, this is native:

 public static void waitForElementToAppear(Driver driver, By selector, long timeOutInSeconds, String timeOutMessage) { try { WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds); wait.until(ExpectedConditions.visibilityOfElementLocated(selector)); } catch (TimeoutException e) { throw new IllegalStateException(timeOutMessage); } } 
+3
Jun 03 '13 at 11:16
source share

This works for me every time:

  if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){ //THEN CLICK ON THE SUBMIT BUTTON }else{ //DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE } 
+2
Jun 17 '14 at 2:19
source share

I have expanded the implementation of Selenium WebDriver, in my case HtmlUnitDriver exposes a method

 public boolean isElementPresent(By by){} 

like this:

  • check if the page is loaded during the timeout period.
  • Once the page is loaded, I lower the implicit WebDriver timeout to a few milliseconds, in my case 100 mills should probably also work with 0 mills.
  • calling findElements (By), WebDriver, even if it does not find the element, will only wait for the amount of time from above.
  • return an implicit wait time to load the next page.

Here is my code:

 import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; public class CustomHtmlUnitDriver extends HtmlUnitDriver { public static final long DEFAULT_TIMEOUT_SECONDS = 30; private long timeout = DEFAULT_TIMEOUT_SECONDS; public long getTimeout() { return timeout; } public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isElementPresent(By by) { boolean isPresent = true; waitForLoad(); //search for elements and check if list is empty if (this.findElements(by).isEmpty()) { isPresent = false; } //rise back implicitly wait time this.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS); return isPresent; } public void waitForLoad() { ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver wd) { //this will tel if page is loaded return "complete".equals(((JavascriptExecutor) wd).executeScript("return document.readyState")); } }; WebDriverWait wait = new WebDriverWait(this, timeout); //wait for page complete wait.until(pageLoadCondition); //lower implicitly wait time this.manage().timeouts().implicitlyWait(100, TimeUnit.MILLISECONDS); } } 

Using:

 CustomHtmlUnitDriver wd = new CustomHtmlUnitDriver(); wd.get("http://example.org"); if (wd.isElementPresent(By.id("Accept"))) { wd.findElement(By.id("Accept")).click(); } else { System.out.println("Accept button not found on page"); } 
+1
May 29 '14 at 15:54
source share

Write the following method using Java:

 protected boolean isElementPresent(By by){ try{ driver.findElement(by); return true; } catch(NoSuchElementException e){ return false; } } 

Call the above method at the time of approval.

+1
Mar 16 '15 at 7:03
source share
 String link = driver.findElement(By.linkText(linkText)).getAttribute("href") 

This will give you the link the item points to.

0
Dec 19 '12 at 19:52
source share

With version 2.21.0 of selenium-java.jar you can do this;

 driver.findElement(By.id("...")).isDisplayed() 
-5
Apr 25 2018-12-12T00:
source share

As I understand it, this is the standard way to use the web driver.

-6
Jun 29 '11 at 13:21
source share



All Articles