Arnab
Arnab

Reputation: 271

OpenQA.Selenium.NoSuchElementException was unhandled by user code in c# selenium

I want to wait my selenium programe for max 30 seconds (GlobalVar.timetomaximumwait) with explicit wait.But when ever its unable to locate the element its pausing at wait.until(...) line and displaying OpenQA.Selenium.NoSuchElementException was unhandled by user code If i press continue or press F10 its trying again to find the element and continuing the same for my defined time spam. Not able to understand why the programme paused and the error message is coming in between. I am using VS2010, c#, selenium 2.45,Ie 9

Any kind of help is much appreciated .

 public string SetValueInTextBox(string InputData, string xPathVal)
        {
            try
            {
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(GlobalVar.timetomaximumwait));
                 wait.Until<IWebElement>((d) =>
                {
                    return d.FindElement(By.XPath(xPathVal));
                });
                 IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));

               // IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));


                elementHighlight(TargetElement);
                TargetElement.Clear();
                TargetElement.SendKeys(InputData);

                //driver.FindElement(By.XPath(xPathVal)).SendKeys(InputData);


                return "Pass";
            }
            catch (Exception e)
            {
                return "Fail";
            }
            finally
            {
               // string SSName = "temp.jpg";
                TakeScreenshot("SetValueInTextBox");

            }
        }

Upvotes: 2

Views: 1378

Answers (1)

aholt
aholt

Reputation: 2971

The problem lies here:

wait.Until<IWebElement>((d) =>
{
    return d.FindElement(By.XPath(xPathVal));
});

You need to handle the exception that gets thrown when the element is not found.

wait.Until<IWebElement>((d) =>
{
    try
    {
        return d.FindElement(By.XPath(xPathVal));
    }
    catch(NoSuchElementException e)
    {
        return null;
    }
});

I would suggest adding in some logging into the catch block, so you know every time the driver fails to find the element.

Upvotes: 4

Related Questions