我收到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/