java - 我收到 StaleElementReferenceException : element is not attached to the page document

标签 java selenium selenium-webdriver staleelementreferenceexception

HTMLCODE

我收到StaleElementReferenceException:元素未附加到页面文档。我浏览了 StackOverflow 中已有的一些解决方案。它不起作用,并且继续抛出相同的错误。这是我正在使用的代码,它引发了陈旧的引用错误

WebElement table2 = driver.findElement(By.cssSelector("body > div:nth-child(74) > div.sp-palette-container"));
List<WebElement> allrows2 = table2.findElements(By.tagName("div"));

    for(WebElement row2: allrows2){
        List<WebElement> cells = row2.findElements(By.tagName("span"));
        for(WebElement cell:cells){
                if (cell.getAttribute("title").equals("rgb(0, 158, 236)")) {
                cell.click(); 

                }          
          }
    } 

最佳答案

因为单击找到的单元格会导致当前页面上发生一些 HTML 更改,由于此更改,selenium 会将页面(单击后)视为"new"页面(即使实际上没有重定向到另一个页面)。

在循环的下一次迭代中,循环仍然引用属于“上一个”页面的元素,这是“StateElementReference”异常的根本原因。

因此,您需要在"new"页面上再次找到这些元素,以更改元素的引用来自"new"页面。

WebElement table2 = driver.findElement(By.cssSelector("body > div:nth-child(74) > div.sp-palette-container"));
List<WebElement> allrows2 = table2.findElements(By.tagName("div"));

int rowSize, cellSize = 0;
rowSize = allrows2.sie();

for(int rowIndex=0;rowIndex<rowSize;rowIndex++){
    WebElement row2 = allrows2.get(rowIndex);
    List<WebElement> cells = row2.findElements(By.tagName("span"));
    cellSize = cells.size();

    for(int cellIndex=0;cellIndex<cellSize;cellIndex++){
        WebElement cell = cells.get(cellIndex);

        if (cell.getAttribute("title").equals("rgb(0, 158, 236)")) {
            cell.click();
            // find cells again on "new" page
            cells = row2.findElements(By.tagName("span"));
             // find rows again on "new" page
            allrows2 = table2.findElements(By.tagName("div"));
        }
    }
}

关于java - 我收到 StaleElementReferenceException : element is not attached to the page document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49173013/

相关文章:

java - 如何为 Selenium Java FirefoxDriver 设置环境变量?

Selenium firefox 驱动力 https

java - 如何在 Selenium Java 中使用 CTRL + v 将文本值粘贴到输入字段中?

selenium - 使用 XPath 在 Selenium 中查找元素

java - 如何在 Android 中使用头文件 (.h)

java - ORM 在 JPA 中同时使用两种策略映射继承?

java - 悬停属性的 Selen 测试

java - 如何在内存方面为四叉树叶的 "organize"数据结构?

java - 如何使用 JNI 传递和接收对象

selenium - 如何使用selenium IDE录制弹出窗口