testing qwerty
testing qwerty

Reputation: 105

OpenQA.Selenium.NoSuchElementException - C# Selenium

A text has to be entered in a Textbox, a list auto-extends, and I need to select the first item. But it fails due to the exception; OpenQA.Selenium.NoSuchElementException. I tried using wait.Until(), but facing the same error.

Screenshot

try
{
     IWebElement cityList = driver.FindElement(By.XPath("value"));
     MouseClick(driver, cityList);
}
catch (OpenQA.Selenium.NoSuchElementException ex)
{
     IWebElement cityList = driver.FindElement(By.XPath("value"));
     MouseClick(driver, cityList);
}

Edit

HTML code:

<input name="ctl00$cphmain$txtCity" type="text" maxlength="50" id="ctl00_cphmain_txtCity" class="mandsearchtxtbox" onkeypress="javascript:return ValidateInputAlphabeticValuesOnly(event);" onblur="javascript:return checkItemMsg(this)" style="width:180px;" autocomplete="off">
<div class="AutoExtenderHighlight">AMANDOLUWA</div>

Code with wait.Until()

WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    wait.Until<IWebElement>((d) =>
        {
            try
            {
                return d.FindElement(By.XPath("//*[@id='citydiv']/div"));
                MouseClick(driver, driver.FindElement(By.XPath("//*[@id='citydiv']/div")));
            }
            catch (OpenQA.Selenium.NoSuchElementException ex)
            {
                return null;
                MouseClick(driver, driver.FindElement(By.XPath("//*[@id='citydiv']/div")));
            }
        });

Edit 2

HTML code for WebDriverException(Button)

HTML code

Upvotes: 3

Views: 11767

Answers (1)

Guy
Guy

Reputation: 50949

According to the html you posted the id is ctl00_cphmain_txtCity, not citydiv.

Your wait.Until implementation will return IWebElement or null, it will never reach to the MouseClick method. It will also check if the element exists, not visible.

You can use the built in expected conditions class

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@id='ctl00_cphmain_txtCity']/div")));
element.Click();

If you want your own implementation you can do something like

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement option = wait.Until<IWebElement>((d) =>
{
    try
    {
        IWebElement element = d.FindElement(By.XPath("//*[@id='ctl00_cphmain_txtCity']/div"));
        if (element.Displayed)
        {
            return element;
        }
    }
    catch (NoSuchElementException ) { }
    catch (StaleElementReferenceException) { }

    return null;
});

option.Click();

Although I commander you use the built in functionality.

Upvotes: 4

Related Questions