【问题标题】:Getting stale element exception while iterating over element loop迭代元素循环时获取陈旧元素异常
【发布时间】:2016-06-17 04:29:20
【问题描述】:

构建一个迭代器以遍历 WebElement 列表:

List<WebElement> rowElements = driver.findElements(By.tagName("tr"));
for (WebElement element : rowElements)
{
    List<WebElement> elements = element.findElements(By.tagName("td"));
    for (WebElement localElement : elements)
    {
        localElement.getText();// Next localElement is stale after select statement is run.**
        if (!localElement.getText().equalsIgnoreCase(""))
        {
            Select newSelectElement = new Select(driver.findElement(By.tagName("select")));
            newSelectElement.selectByValue("value to select");// This causes a page refresh through Ajax call.
            final WebDriverWait wait = new WebDriverWait(driver, 30);
            wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("ajaxStatusModalPanelContainer")));
        }
    } // inner "For" loop ends
}

所以现在的问题是:

如果我尝试在localElement 上执行任何命令,则在生成ajax 调用的select 操作之后。在点击之后的这一点上,localElement 已过时,您无法再次访问它,除非您执行一个全新的例程以使用任何By 调用再次定位它。

有没有办法处理这种情况并做点什么 喜欢WebElement.refresh() 以消除当前或下一个即将到来的内容 元素。我使用java 作为代码语言。

【问题讨论】:

  • 您的 HTML 代码在哪里?你能重新编辑你的缩进吗?很难说出你的“for”循环中有多少代码
  • 我已经更新了代码主体,请看一下。这里我正在尝试遍历具有选择下拉列表的 td 元素,选择任何值页面刷新器,并且对于下一个即将到来的 td 元素应用程序抛出陈旧元素异常。
  • 我认为你的问题在于这一行,localElement = driver.findElement(By.tag("select"));尝试使用不同的变量名,这个变量名已经在你的内部 For 循环的开头使用了。
  • 我已尝试更改无法解决问题的元素。我也在编辑代码,请看一下。
  • 你需要重新查找元素,因为刷新它现在已经过时了。

标签: java selenium selenium-webdriver


【解决方案1】:

是的,您必须在所有元素过时后再次获取它们。更新SELECT 会导致相关元素的更新,因此它们会过时。然后您必须重新获取它们。

如果您能提供有关您的场景和相关 HTML 的更多详细信息,我或许可以帮助您重写代码以使其正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2018-12-05
    相关资源
    最近更新 更多