Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Selenium - Is there any way to check if the Element Exists or not without throwing NoSuchElementException

Is there any way to check if the element exists on the page without throwing an exception using selenium C#.

like image 601
user4472042 Avatar asked Jan 09 '23 01:01

user4472042


2 Answers

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

like image 181
Arran Avatar answered Jan 11 '23 15:01

Arran


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;
    }
}
like image 40
Saifur Avatar answered Jan 11 '23 14:01

Saifur