Programerszz Programerszz - 1 month ago 22
C# Question

How to check if Element exists in c# Selenium drivers

So I have this c# winform using Firefox selenium webdriers.

Basically i need it to check if an element exists and if it doesn't click on a different one. If there is a video and after it is watched it become W_VIEWED

Here is what i got so far

driver.FindElement(By.XPath("//div[@class='video']/a")).Click();
else {
driver.FindElement(By.XPath("//div[@class='W_VIEWED']/a")).Click();
}


Error 3 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement 242

Kind of new to c# selenium. Thank you for help.

Answer

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
            }