【问题标题】:WebDriverWait throws Timeout instead of NoSuch ElementExceptionWebDriverWait 抛出 Timeout 而不是 NoSuch ElementException
【发布时间】:2019-12-12 17:27:44
【问题描述】:

我正在使用WebDriverWait 来查找几秒钟后可见的元素。 我已经声明了最多 10 秒的时间来等待该特定元素

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

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

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

【问题讨论】:

  • TimeOutException 是使用 WeDriverWait 时的预期行为。它需要 30 秒而不是 10 秒,可能是因为您在某处设置了 implicitlyWait
  • @Guy 您应该将其添加为答案。太完美了
  • 在初始化浏览器时,正在使用 ImplicitWait 30 秒。在那之后,我没有在哪里使用它。其余时间我都在使用 FluentWait。最初的浏览器告诉我,我们必须只使用一次隐式来给时间加载所有的 WebElement ???如果我们不使用隐式并且在初始化浏览器时只专注于显式/流利,那么根本不使用隐式是不是很糟糕......?它是否有效或导致某些问题导致页面未完全加载?

标签: selenium selenium-webdriver webdriver webdriverwait timeoutexception


【解决方案1】:

你没看错。根据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,返回所需的元素/元素,而如果失败,则抛出 timeout 异常。


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

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"));

从您的问题中不清楚为什么抛出 TimeOutException 需要超过 30 秒(大约),但最可能的原因是,尽管您已将 WebDriverWait 的持续时间设置为 10 秒,您还诱导了ImplicitlyWait 以及根据documentation 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

【讨论】:

  • 正如@DebanjanB 提到的,请注意你在初始化浏览器后必须给出的隐式等待,我有一个类似的问题,在初始化驱动程序后我设置了 30 秒的隐式等待,所以总是需要即使明确的等待时间是 10 秒,也要 30 秒超时。
【解决方案2】:

根据WebDriverWait class source

Wait 将忽略默认情况下遇到(抛出)的 NotFoundException 实例 '直到'条件,并立即传播所有其他条件。您可以添加更多忽略 通过调用忽略列表(添加例外)

NotFoundException 是以下异常的超类:

  • NoAlertPresentException
  • NoSuchContextException
  • NoSuchCookieException
  • NoSuchElementException
  • NoSuchFrameException
  • NoSuchWindowException

因此,在使用 WebDriverWait 时您不会看到 NoSuchElement 异常。

也可能是您的元素实际上 存在DOM 中,但由于具有即 display:none CSS property 而它不可见,因此您可以考虑改用 presenceOfElementLocated 条件。

更多信息:How to use Selenium to test web applications using AJAX technology

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2018-09-23
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2017-04-01
    相关资源
    最近更新 更多