首页 > 解决方案 > WebDriverWait 抛出 Timeout 而不是 NoSuch ElementException

问题描述

WebDriverWait用来寻找几秒钟后可见的元素。我已经声明了最多 10 秒的时间来等待那个特定的元素

WeDriverWait wait = new WebDriverWait(driver, 10)
                    .until(ExpectedConditions.visibilityOfElement("path"));

现在我的期望是,如果元素在 10 秒内不可见,那么我应该NoSuchElementException在第 11 秒后得到,但它需要超过 30 秒(大约)并抛出TimeOut Exception

提前感谢您的建议和澄清......!!!

标签: seleniumselenium-webdriverwebdriverwebdriverwaittimeoutexception

解决方案


你没看错。根据WebDriverWait()的文档,构造函数是:

  • WebDriverWait(WebDriver driver, java.time.Clock clock, Sleeper sleeper, long timeOutInSeconds, long sleepTimeOut)
  • WebDriverWait(WebDriver driver, long timeOutInSeconds)
  • WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis)

对于成功的WebDriverWait,返回所需的元素/元素,而如果失败则抛出超时异常。


但是,您的代码块中有一个小问题:

WeDriverWait wait = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElement("path"));    

WeDriverWait返回的是所需元素,而不是 的实例。因此,您需要将行更改为:

WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElement("path"));

以逐步的方式:

WeDriverWait wait = new WebDriverWait(driver, 10)
WebElement element = wait.until(ExpectedConditions.visibilityOfElement("path"));

从您的问题中不清楚为什么需要超过 30 秒(大约)来抛出TimeOutException但最可能的原因是,尽管您已将WebDriverWait的持续时间设置为10秒,但您也已经诱导了ImplicitlyWait并且按照文档 WARNING: Do not mix implicit and explicit waits! Doing so can cause unpredictable wait times. For example, setting an implicit wait of 10 seconds and an explicit wait of 15 seconds could cause a timeout to occur after 20 seconds。_


推荐阅读