0

Even though my code is enclosed in a try block, I am still getting an unhandled exception, "An exception of type OpenQA.Selenium.NoSuchElementException occurred in WebDriver.dll but was not handled in user code.

Here is the code:

        try
        {

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));

            switch (findBy)
            {
                case SeleniumFindBy.ById:
                    itemtext = wait.Until(d => d.FindElement(By.Id(elementId)).Text);
                    break;

                case SeleniumFindBy.ByName:
                    itemtext = wait.Until(d => d.FindElement(By.Name(elementId)).Text);
                    break;

                case SeleniumFindBy.ByLinkText:
                    itemtext = wait.Until(d => d.FindElement(By.LinkText(elementId)).Text);
                    break;

                case SeleniumFindBy.ByPartialLinkText:
                    itemtext = wait.Until(d => d.FindElement(By.PartialLinkText(elementId)).Text);
                    break;

                case SeleniumFindBy.ByXPath:
                    itemtext = wait.Until(d => d.FindElement(By.XPath(elementId)).Text);
                    break;

                case SeleniumFindBy.CssSelector:
                    itemtext = wait.Until(d => d.FindElement(By.CssSelector(elementId)).Text);
                    break;
            }
        }
        catch (OpenQA.Selenium.NoSuchElementException ex)
        {
            LastError = elementId + "," + ex.Message;
        }
        catch (Exception ex)
        {
            LastError = elementId + "," + ex.Message;
        }

1 Answers1

0

Though you are using lambda expression as:

itemtext = wait.Until(d => d.FindElement(By.Id(elementId)).Text);

The lambda expression still relies on FindElement() method.


FindElement Method

ISearchContext.FindElement Method finds the first IWebElement using the given method.

Syntax:

IWebElement FindElement(
    By by
)

Return Value

Type: IWebElement
The first matching IWebElement on the current context.

Exception: NoSuchElementException


This usecase

As the inner FindElement Method() fails, hence you see NoSuchElementException.

Solution

As a solution you can handle the exception that gets thrown when the element is not found within a try-catch{} block as follows:

itemtext = wait.Until<IWebElement>((d) =>
{
    try
    {
        return d.FindElement(By.Id(elementId).Text);
    }
    catch(NoSuchElementException e)
    {
        return null;
    }
});
break;
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352