当我试图点击下拉列表id:
时,我得到了这个错误stale element reference: element is not attached to the page document
我想用这个代码:
boolean staleElement = true;
while(staleElement)
{
try{
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement element = driver.findElement(By.id(dropDownId));
wait.until(ExpectedConditions.elementToBeClickable(element));
element.click();
staleElement = false;
}
catch(StaleElementReferenceException e)
{
staleElement = true;
Thread.sleep(200);
}
}
是否有一些方法来防止无限循环或更好的方法来点击id后,我得到这个异常?
总的来说你的代码还不错。为了避免无限循环,您可以在那里添加某种计数器,例如,在单击元素失败10次的情况下,测试将失败。
如果你在try
块内得到Element is not clickable at point
异常,你可以尝试使用visibilityOfElementLocated
预期条件而不是elementToBeClickable
。
如果这仍然不够,你可以在wait.until(ExpectedConditions.visibilityOfElementLocated(element));
和element.click();
命令之间添加一个短暂的延迟,让元素在点击元素之前最终呈现在页面上。