9

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

Right now I have something that looks like this:

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

However, when that element that has the value of 9 does not exist, it returns an error. Is there a way I can check to see if it exists, or something of that sort?

3 Answers 3

16

There are several options. I recommend these.
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 element, get it if there are 1 or more elements.

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) { ... }

2
  • What kind of programming language is that? Looks like Java mixed with JavaScript. Does Java have a new feature like auto-detecting a type of a variable? Something like auto in C++? And what does this keyword near the type of the first argument mean?
    – ibodi
    Aug 30, 2018 at 18:43
  • @ibodi The question was for C#, so I'm pretty sure this is C#. Mar 1, 2020 at 4:41
0

You should be able to do something like:

//Method :
public static bool IsElementPresent_byCssSelector(string elementName)
{
    try { Driver.FindElement(By.CssSelector(elementName)); }
    catch (NoSuchElementException) { return false; }
    catch (StaleElementReferenceException) { return false; }
    return true;
}

//Usage :
var test = driver.IsElementPresent_byCssSelector("a[data-value*='09.0']");

if(test)
{
    //do something
}
1
  • Hmm the method did not get attached. Updated the above.
    – Dazed
    Nov 23, 2016 at 16:39
0

Using Dazed's reply, I do a little modification to pass any selector.

//Method :
public bool ElementExists(By by)
{
     try 
     { 
         Driver.FindElement(by); 
     }
     catch (NoSuchElementException) 
     { 
          return false; 
     }
     catch (StaleElementReferenceException) 
     { 
          return false; 
     }
     return true;
}

//Usage:
if (ElementExists(By.XPath("...")))
   ...
if (ElementExists(By.Id("...")))
   ...
if (ElementExists(By.CssSelector("...")))
   ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.