Selenium c# wait.until(expectedconditions)... 函数无法在屏幕上找到 objects/elements

Selenium c# wait.until(expectedconditions)... function fails to find objects/elements on screen

我是使用 selenium Webdriver 和编写 c# 的新手。我在我的脚本中使用了很多 thread.sleep() 命令来确保 Selenium 不会尝试点击得太快。经过大量研究,我发现这是不受欢迎的,并且有 "better" 方法可以做到这一点,所以我开始使用:-

wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("FieldId")));

Wait在另一个class中定义为:-

wait = new WebDriverWait(driver, new TimeSpan(0, 0, 0, 10));

我只能让它工作 运行 脚本的 2/10 倍而没有得到 :

No such element exception: cannot locate element......

现在我已经停止使用 thread.sleep,我有很多关于这个问题的例子。经过大量研究,我总是发现这是建议的方式,但它似乎完全不可靠。我错过了什么吗?该元素在 2 秒后始终存在,并且在 10 秒过去之前发生错误。我已经阅读了至少 10 篇其他听起来相似的帖子,但其中 none 有一个有效的解决方案......除了 Thread.Sleep(5000) !

尝试在创建后将 NoSuchElementException 类型添加到服务员的 IgnoreExceptionTypes 中。

wait = new WebDriverWait(driver, new TimeSpan(0, 0, 0, 10));
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("FieldId")));

一般来说,如果服务员在您指定的超时到期之前返回,那是因为发生了当前未被忽略的异常。

WebDriverWait class is derived from the DefaultWait class。您可以在 github 上查看这两者,我发现这对理解如何使用它非常有帮助。