selenium - org.openqa.selenium.StaleElementReferenceException:过时元素引用:元素未附加到页面文档以查找元素
问题描述
我使用此代码单击
List<WebElement> list = driver.findElements(By.xpath("//div[@class='ag-center-cols-container']//div"));
// check for list elements and print all found elements
if(!list.isEmpty())
{
for (WebElement element : list)
{
// System.out.println("Found inner WebElement " + element.getText());
}
}
// iterate sub-elements
for ( WebElement element : list )
{
System.out.println("Searching for " + element.getText());
if(element.getText().equals(valueToSelect))
{
new WebDriverWait(driver, 30).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@class='overlay ng-star-inserted']")));
element.click();
break; // We need to put break because the loop will continue and we will get exception
}
}
但有时我会在这一行收到此错误element.getText()
:
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
你知道我如何实现一个lister来解决这个问题>
解决方案
org.openqa.selenium.StaleElementReferenceException:
表示对元素的引用现在是“陈旧的”——该元素不再出现在页面的 DOM 上。这种期望的原因可能是你DOM
得到了更新或刷新。例如,在执行类似click()
您的操作后,DOM
可能会得到更新或刷新。在这个时候,当你试图在你上面找到一个元素时,DOM
你会遇到这个错误。
您必须在更新或刷新中重新找到该元素DOM
但有时我会在这一行 element.getText() 收到此错误:
创建一个可重用的方法来处理此异常。
代码:
public static String getTextFromElement(WebElement element, WebDriver driver) {
try {
return element.getText();
} catch (org.openqa.selenium.StaleElementReferenceException e) {
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOf(element));
return element.getText();
}
}
例如,您可以通过这种方式调用。
System.out.println("Found inner WebElement " + getTextFromElement(element, driver));
推荐阅读
- javascript - 根据状态更改按钮的 className 无法正常工作
- python - 保持 python 调度程序脚本在 Windows 上运行
- c++ - 恒定时间构建/重新解释兼容数据的向量?
- pandas - 如何在蚁群优化中绘制 ROC 曲线(基本蚂蚁矿工)
- hyperledger-composer - Hyperledger Composer ACL 条件中绑定变量的描述
- mysql - 相关子查询在 MySQL 中工作,但在 Oracle 中不返回结果
- java - 单个生产者,多个阻塞队列,多个消费者
- node.js - 允许我随时访问“种子”的随机数生成器
- go - 如何取两个大浮点数
- vba - 如何判断何时添加了 Word 评论