【问题标题】:Ocasional InvalidElementStateException or ElementNotVisibleException when calling SendKeys on input在输入上调用 SendKeys 时偶尔出现 InvalidElementStateException 或 ElementNotVisibleException
【发布时间】:2017-02-12 00:27:13
【问题描述】:

我有这个代码:

IWebDriver driver = new FirefoxDriver();
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
//Go to the powerbi site
driver.Navigate().GoToUrl("https://powerbi.microsoft.com/en-us/");
//Go to the page with login form
driver.FindElement(By.XPath("html/body/div[2]/header/nav/div/ul[3]/li[1]/a")).Click();
//Fill in email field
driver.FindElement(By.XPath("//*[@id='cred_userid_inputtext']")).SendKeys("example@gmail.com");

当我在我的计算机上启动此代码时,一切正常,没有错误。但是当我在老板的计算机上启动这段代码时,有时它可以工作,有时它不能。

发生错误时,它始终位于代码的最后一行。我不记得到底是哪个错误:InvalidElementStateException(当目标元素未启用时)或 ElementNotVisibleException(当目标元素不可见时)。

我想整个事情都在 Click() 方法上。 documentation 说:

单击此元素。如果单击导致加载新页面,则 Click() 方法将尝试阻止,直到页面加载完毕。

我不太明白它是如何试图阻止的。

【问题讨论】:

    标签: c# selenium selenium-webdriver


    【解决方案1】:

    点击按钮后,您的输入似乎并不总是准备就绪。 您应该在发送密钥之前等待它:

    试试这个而不是你的最后一行:

    WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,5));
    var input = wait.Until(ElementIsClickable(By.XPath("//*[@id='cred_userid_inputtext']")));
    input.SendKeys("example@gmail.com");
    

    为了进行检查,您应该创建一个 ElementIsClickable 函数,该函数返回一个委托,正如 this answer 所示:

    public static Func<IWebDriver, IWebElement> ElementIsClickable(By locator)
    {
        return driver =>
        {
            var element = driver.FindElement(locator);
            return (element != null && element.Displayed && element.Enabled) ? element : null;
        };
    }
    

    另外,请记住,要使用 WebDriverWait 类,您可能需要将 Selenium.WebDriverSelenium.Support 包导入您的项目,正如 this answer 建议的那样。

    【讨论】:

    • 谢谢,但对我来说,这个功能 (ElementIsClickable) 不起作用。我使用 ExpectedConditions.ElementToBeClickable() 函数,这里的代码可以正常工作:WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30)); var signIn = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("xpath"))); signIn.Click();我为上面代码的出现道歉:)
    【解决方案2】:

    它偶尔会出现,因为有时从 DOM 加载元素需要时间,这会导致 InvalidElementStateException 或 ElementNotVisibleException 等异常。 我运行了你的 sn-ps 代码。 它运行良好,尝试分离动作并找到元素。

    WebElement element = driver.findElement(By.xpath(".//xyz"/);
    element.sendkeys("data");
    

    这可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      相关资源
      最近更新 更多