OpenQA.Selenium.NoSuchElementException - C#Selenium

时间:2017-05-25 11:33:04

标签: c# selenium

必须在文本框中输入文本,自动扩展列表,然后我需要选择第一个项目。但由于例外,它失败了; OpenQA.Selenium.NoSuchElementException。我尝试使用wait.Until(),但面临同样的错误。

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);
}

修改

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>

使用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")));
            }
        });

修改2

WebDriverException(Button)的HTML代码

HTML code

1 个答案:

答案 0 :(得分:2)

根据你发布的html,我的ID是ctl00_cphmain_txtCity,而不是citydiv

您的wait.Until实施将返回IWebElementnull,它永远不会达到MouseClick方法。它还将检查元素是否存在,不可见。

您可以使用内置的expected conditions

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

如果您想要自己的实现,可以执行类似

的操作
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();

虽然我指挥你使用内置功能。<​​/ p>