.NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用

时间:2015-03-04 20:42:24

标签: c# .net selenium nosuchelementexception

我们有一个.NET 4.5,MVC,C#项目。我们正在使用Selenium进行UI测试,测试会在我们wait.Until()的行上间歇性地失败。一个这样的例子是:

NoSuchElementException was unhandled by user code
An exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll but was not handled in user code
Additional information: Unable to locate element: {"method":"css selector","selector":"#assessment-472 .status-PushedToSEAS"}

它就在这里抛出:

Thread.Sleep(600);
wait.Until(drv => drv.FindElement(By.CssSelector("#" + assessmentQueueId + " .status-PushedToSEAS")));

我可以看到浏览器打开,我看到它到达那一点,我可以检查元素以查看该元素是否存在。它的id完全正确。

我们遇到了这个问题很多,到目前为止,解决方案是在其前面抛出Thread.Sleep(600)(或类似的时间)。 wait.Until()的全部要点是不必这样做,这使我们的测试套件变得非常长。另外,正如您在上面的示例中所看到的,有时即使在Thread.Sleep()前面放置问题我们也会遇到问题,我们必须延长时间。

为什么.NET Selenium的WebDriver.Until()无法正常工作,而且只是等待一段时间后,有不同的方法可以做同样的事情吗?同样,问题是间歇性的,这意味着它有时只会发生,并且可能发生在任何数量的wait.Until()语句中,而不仅仅是显示的语句!

修改

这是一个类变量。 private WebDriverWait wait;

它实例化如下:

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

2 个答案:

答案 0 :(得分:1)

我决定不使用WebDriverWait.Until(),而是在主驱动程序上使用隐式等待:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

我完全赞同this answer关于给我这个想法的另一个问题。

答案 1 :(得分:0)

public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
        {
            try
            {
                if (timeoutInSeconds > 0)
                {
                    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
                    return wait.Until(drv => drv.FindElement(by));
                }
                return driver.FindElement(by);
            }
            catch
            {
                throw;
            }
        }

或者如果你有

  

NoSuchElementException异常

试试这段代码

 try
        {
            if (timeoutInSeconds > 0)
            {
                var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)).Until(ExpectedConditions.ElementIsVisible(by));
            }
            return driver.FindElement(by);
        }
        catch(Exception e)
        {
            throw;
        }