How to check if Element exists in c# Selenium drivers

You can check element exits or not using

bool isElementDisplayed = driver.findElement(By.xpath("element")).isDisplayed()

Remember, findElementthrows exception if it doesn't find element, so you need to properly handle it.

In one of my application I handled exception by checking element in separate function,

    private bool IsElementPresent(By by)
    {
        try
        {
            driver.FindElement(by);
            return true;
        }
        catch (NoSuchElementException)
        {
            return false;
        }
    }

Call function,

            if (IsElementPresent(By.Id("element name")))
            {
                //do if exists
            }
            else
            {
                //do if does not exists
            }

You can use FindElements with an "s" to determine if it exists, since FindElement results in an Exception. If FindElements does not return an element then it returns an empty list.

List<IWebElement> elementList = new List<IWebElement>();
elementList.AddRange(driver.FindElements(By.XPath("//input[@att='something']")));

if(elementList.Count > 0)
{
 //If the count is greater than 0 your element exists.
   elementList[0].Click();
}

So I recently figured out another way, which is MUCH faster. If your element has a unique ID or some attribute that exists no where else on the page, you can check the PageSource.

driver.PageSource.Contains("UniqueID");

It checks the page to see if the ID or other unique text exists. This happens almost instantaneously, as opposed to using a Try/Catch statement, which takes ~20 seconds. FindElements takes a long time to run too.

Tags:

C#

Selenium