Check if an item exists in Selenium

I want to check if an element exists in Selenium, and if so, give it a name.

I now have something similar to this:

IWebElement size9 = driver.FindElement(By.CssSelector("a[data-value*='09.0']")); 

However, if this element, which has a value of 9, does not exist, it returns an error. Is there a way to check if it exists or something like that?

+7
c # selenium
source share
2 answers

There are several options. I recommend them.
1. Create a method or web driver extension.

 public static IWebElement FindElementIfExists(this IWebDriver driver, By by) { var elements = driver.FindElements(by); return (elements.Count >=1) ? elements.First() : null; } // Usage var element = driver.FindElementIfExists(By.CssSelector("a[data-value*='09.0']")); 


2. Count the item, get it if there are 1 or more items.

 By by = By.CssSelector("a[data-value*='09.0']"); var element = driver.FindElements(by).Count >= 1 ? driver.FindElement(by) : null; 

Then you can check if(element != null) { ... }

+9
source share

You should be able to do something like:

  public static bool IsElementPresent_byCssSelector(string elementName) { try { Driver.FindElement(By.CssSelector(elementName)); } catch (NoSuchElementException) { return false; } catch (StaleElementReferenceException) { return false; } return true; } var test = driver.IsElementPresent_byCssSelector("a[data-value*='09.0']"); if(test) { //do something } 
0
source share

All Articles