Is there any way to check if the element exists on the page without throwing an exception using selenium C#.
Asked
Active
Viewed 5,601 times
3 Answers
10
Your alternative might be to use .FindElements
. Given a selector that doesn't match anything it'll return an empty list as opposed to throw an exception.
var elementExists = driver.FindElements(By.ClassName("something")).Any();
Any
is a LINQ method that merely checks if the list contains something (think .Count == 0
).

Arran
- 24,648
- 6
- 68
- 78
1
I would use try catch block with explicit
wait
public bool CheckElementExist(string state)
{
//Write the selector carefully.
By byCss = By.CssSelector("#view-" + state + "");
try
{
//Explicit wait to check if element exist for 10s
new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byCss));
return true;
}
catch (NoSuchElementException)
{
return false;
}
}

Saifur
- 16,081
- 6
- 49
- 73
-1
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
There is something called an explicit and implicit wait take a look at the above link.

Ya Wang
- 1,758
- 1
- 19
- 41