Search code examples
c#seleniumfirefoxxpath

How to check if an element exists?


In my C# Windows Forms application using Firefox Selenium WebDriver I need to check if an element exists and if it doesn't, click a different one. If there is a video, after it is watched it becomes W_VIEWED:

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


Solution

  • You can check if an element exits or not by using

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

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

    In one of my applications, I handled an exception by checking the element in a 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
    }