0

我正在尝试在selenium. 进入子页面,获取数据,返回,进入下一个子页面......不幸的是,exception我出现了

“org.openqa.selenium.StaleElementReferenceException:元素不再有效”

好吧 - 重新加载后它是另一个页面。有任何想法吗?

代码:

List<WebElement> rows = driver.findElements(By.className("detail-card__heading"));
List<WebElement> cols=new ArrayList<WebElement>();
for(int i=0;i<rows.size();i++){
System.out.println("Nr oferty: "+i);
cols=rows.get(i).findElements(By.tagName("div"));
for(WebElement col:cols) {
System.out.print("cell value "+col.getText());
 col.click();
}
 driver.get(CurrentUrl);
}
4

1 回答 1

0

好,我知道了。

您必须了解,当您使用“findElement”时,selenium 存储对相应 DOM 元素的直接引用。它不存储“By”条件。

这意味着每次使用“get(url)”重新加载页面时,由于整个 html 页面都被重新渲染,因此您将丢失所有实际的 selenium 元素。在这种情况下,selenium 会引发“陈旧元素”异常,这意味着引用的 DOM 元素不再存在于 DOM 中。

为避免此错误,您必须在每次迭代中重新找到“行”元素

List<WebElement> rows = driver.findElements(By.className("detail-card__heading"));
List<WebElement> cols=new ArrayList<WebElement>();
for(int i=0;i<rows.size();i++){
    System.out.println("Nr oferty: "+i);
    rows = driver.findElements(By.className("detail-card__heading"));
    cols=rows.get(i).findElements(By.tagName("div"));
    for(WebElement col:cols) {
        System.out.print("cell value "+col.getText());
        col.click();
    }
    driver.get(CurrentUrl);
}
于 2018-01-23T10:20:14.980 回答