Is there any way to check if the element exists on the page without throwing an exception using selenium C#.
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
).
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With