我有一个如下屏幕截图所示的场景:
所以,我构建了一些代码,允许我单击左侧的条形图......每次我这样做都会在右侧显示一个关系条形图。如果左侧的条形图特别大,则右侧的关系条形图可能需要一段时间才能显示。为了解决这个问题,我构建了一个 fluenceWait 方法,如下所示:
public static void fluentWaitOnRelationalBarChartSelector(InternetExplorerDriver driver)
{
WebElement relationalBarSelect = (new WebDriverWait(driver, 20))
.until(ExpectedConditions.elementToBeClickable(By.tagName("rect")));
relationalBarSelect.click();
}
但是,并非总是如此,但有时,我在控制台中收到如下错误:
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element is no longer valid
(WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 33 milliseconds
我不确定的是,当我应用了 20 秒的等待后,为什么会在 33 毫秒后发生超时?有什么办法可以满足这个 StaleElementReferenceException
的需求吗?
如有任何帮助,我们将不胜感激。
最佳答案
StaleElementReferenceException
是一个非常痛苦且非常具体的元素。这通常意味着由于某些特定于您的设置的许多问题,该元素无法与 Selenium 交互。为了解决这个问题,人们使用两种不同的机制(至少据我所知)。 FluentWait
可能会拯救你的生命。类似于以下内容:
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
取自here 。值得一提的是,它允许您等待元素并忽略其他一些异常。
如果这不起作用,则估计可能足以使该元素准备好进行交互的循环次数。不是我最喜欢的,但很有效。
public void StaleElementHandleByID (String elementID){
int count = 0;
while (count < 4){
try {
WebElement yourSlipperyElement= driver.findElement(By.id(elementID));
yourSlipperyElement.click();
} catch (StaleElementReferenceException e){
e.toString();
System.out.println("Trying to recover from a stale element :" + e.getMessage());
count = count+1;
}
count = count+4;
}
取自here
关于java - Selenium fluenceWait 导致 StaleElementReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27546946/