在遍历带分页的表格并使用stalenessOf() 时,出现Selenium的过时元素引用异常——Angular应用程序

前端开发 2026-07-12

我在尝试判断一个值是否出现在带分页的表格中。
如果在当前页未找到该值,我就点击 下一页 按钮并继续搜索。

我遇到了这个异常:

org.openqa.selenium.StaleElementReferenceException: 
stale element reference: stale element not found in the current frame

异常发生在:

String actualText = element.getText().trim();

为什么在循环中我仍然会遇到StaleElementReferenceException?
在带有动态Angular表格的分页中,正确的处理方式是什么?

以下是我的方法:

public boolean isPresent(String expectedValue) {
    while(true) {
        wait.until(ExpectedConditions.visibilityOfElementLocated(tableRows));
        List<WebElement> elements = driver.findElements(tableRows);

        for(WebElement element : elements) {
            String actualText = element.getText().trim();
            if(actualText.equals(expectedValue)) {
                return true;
            }
        }

        By nextButton = By.xpath("//button[@aria-label='Next page']");
        WebElement next = driver.findElement(nextButton);

        if(next.isEnabled()) {
            WebElement firstRow = elements.get(0);
            next.click();
            wait.until(ExpectedConditions.stalenessOf(firstRow));
        } else {
            break;
        }
    }
    return false;
}

解决方案

通过使用catch块,它按预期工作,

如果读取表格时表格被刷新,我会重新获取该行,因此确实会出现stale(过时)的情况

catch (StaleElementReferenceException e) {
                    rows = driver.findElements(tableRows); 
                    if (rows.isEmpty()) {
                        break; 
                    }
                    i = -1; 
                }
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章