如何以及何时实施Selenium WebDriver的刷新(ExpectedCondition <T>条件)?

TDH*_*DHM 10 java selenium selenium-webdriver

我正在通过ExpectedCondtions类的方法,找到一个方法:刷新

我可以理解,当你获得StaleElementReferenceException并且你想要再次检索那个元素时,可以使用该方法,这样可以避免StaleElementReferenceException

我的上述理解可能不正确因此我想证实:

  1. 什么时候refreshed应该使用?
  2. something以下代码的部分代码应该是什么:

wait.until(ExpectedConditions.refreshed(**something**));

有人可以用一个例子解释一下吗?

HaC*_*HaC 10

refreshed在尝试访问新刷新的搜索结果时,该方法对我非常有帮助。试图通过只ExpectedConditions.elementToBeClickable(...)返回来等待搜索结果StaleElementReferenceException。为了解决这个问题,这是一个辅助方法,它会等待并重试最多 30 秒,以便搜索元素刷新和可点击。

public WebElement waitForElementToBeRefreshedAndClickable(WebDriver driver, By by) {
    return new WebDriverWait(driver, 30)
            .until(ExpectedConditions.refreshed(
                    ExpectedConditions.elementToBeClickable(by)));
}
Run Code Online (Sandbox Code Playgroud)

然后点击搜索后的结果:

waitForElementToBeRefreshedAndClickable(driver, By.cssSelector("css_selector_to_search_result_link")).click();
Run Code Online (Sandbox Code Playgroud)

希望这对其他人有帮助。


dda*_*son 8

根据消息来源:

条件的包装器,允许通过重绘来更新元素.这解决了包含两个部分的条件问题:找到一个元素然后检查它上面的某些条件.对于这些条件,可能会找到一个元素,然后在客户端上重新绘制它.发生这种情况时,在检查条件的第二部分时会抛出{@link StaleElementReferenceException}.

所以基本上,这是一个等待对象完成DOM操作的方法.

通常,当您执行driver.findElement 该对象时,表示对象是什么.

当DOM操作并且在单击按钮之后说,向该元素添加一个类.如果您尝试对所述元素执行操作,它将抛出,StaleElementReferenceException 因为现在WebElement返回的现在不代表更新的元素.

refreshed当你期望DOM操作发生时,你将使用,并且你想要等到它在DOM中被操作完成.

例:

<body>
  <button id="myBtn" class="" onmouseover="this.class = \"hovered\";" />
</body>

// pseudo-code
1. WebElement button = driver.findElement(By.id("myBtn")); // right now, if you read the Class, it will return ""
2. button.hoverOver(); // now the class will be "hovered"
3. wait.until(ExpectedConditions.refreshed(button));
4. button = driver.findElement(By.id("myBtn")); // by this point, the DOM manipulation should have finished since we used refreshed.
5. button.getClass();  // will now == "hovered"
Run Code Online (Sandbox Code Playgroud)

请注意,如果您button.click()在第3行执行说明,它将抛出StaleReferenceException,因为此时已经操作了DOM.

在我使用Selenium的这些年里,我从来没有使用过这种情况,所以我认为这是一种"边缘情况"的情况,你很可能甚至不必担心使用它.希望这可以帮助!

  • 根据这里的文档:https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html ExpectedCondition.refreshed()期望另一个ExpectedCondition,而不是WebElement,如您的示例中所示.你能解释或更新你的例子吗?谢谢. (7认同)