首页 >后端开发 >C++ >为什么我的 WebDriverWait 不等待元素?

为什么我的 WebDriverWait 不等待元素?

Patricia Arquette
Patricia Arquette原创
2025-01-03 16:29:39640浏览

Why Isn't My WebDriverWait Waiting for the Element?

WebDriverWait 不等待指定的元素

问题

当实现 WebDriverWait 等待元素出现后再检索其文本时,等待功能似乎被忽略,导致异常。

解释

根本原因:

默认情况下,WebDriverWait 使用轮询间隔定期检查元素是否存在。如果该元素在初始检查期间未立即可用,则后续轮询间隔可能不够频繁,无法捕获该元素的出现,从而导致异常。

解决方案

1.增加轮询频率:

为了确保 WebDriverWait 更频繁地检查元素,请通过将较小值的 TimeSpan 传递给 WebDriverWait 构造函数来增加轮询间隔:

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

2.使用 ExpectedConditions.ElementIsVisible:

或者,您可以使用 SeleniumExtras.WaitHelpers 中的 ExpectedConditions.ElementIsVisible 方法,该方法显式等待元素变得可见并可用于交互。这消除了轮询依赖性:

string messageText = new WebDriverWait(driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementIsVisible(By.ClassName("block-ui-message"))).GetAttribute("innerHTML");

3。使用DotNetSeleniumExtras.WaitHelpers:

如果您使用DotNetSeleniumExtras.WaitHelpers nuget包,您可以直接导入ExpectedConditions类并使用它:

string messageText = new WebDriverWait(driver, TimeSpan.FromSeconds(30)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.ClassName("block-ui-message"))).GetAttribute("innerHTML");

以上是为什么我的 WebDriverWait 不等待元素?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn