且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Selenium WebDriver:流畅的等待按预期工作,但隐式等待没有

更新时间:2022-12-15 16:28:41

记住几个场景是有区别的:

Remember that there is a difference between several scenarios:

  • DOM 中根本不存在的元素.
  • 存在于 DOM 中但不可见的元素.
  • 存在于 DOM 中但未启用的元素.(即可点击)

我的猜测是,如果某些页面使用 javascript 显示,则这些元素已经存在于浏览器 DOM 中,但不可见.隐式等待只等待一个元素出现在 DOM 中,因此它会立即返回,但是当您尝试与该元素交互时,您会收到 NoSuchElementException.您可以通过编写一个显式等待元素可见或可点击的辅助方法来检验这个假设.

My guess is that if some of the page is being displayed with javascript, the elements are already present in the browser DOM, but are not visible. The implicit wait only waits for an element to appear in the DOM, so it returns immediately, but when you try to interact with the element you get a NoSuchElementException. You could test this hypothesis by writing a helper method that explicits waits for an element to be be visible or clickable.

一些例子(Java):

Some examples (in Java):

public WebElement getWhenVisible(By locator, int timeout) {
    WebElement element = null;
    WebDriverWait wait = new WebDriverWait(driver, timeout);
    element = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
    return element;
}

public void clickWhenReady(By locator, int timeout) {
    WebDriverWait wait = new WebDriverWait(driver, timeout);
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(locator));
    element.click();
}