【问题标题】:Selenium org.openqa.selenium.StaleElementReferenceException: Element is no longer validSelenium org.openqa.selenium.StaleElementReferenceException:元素不再有效
【发布时间】:2018-01-23 10:13:26
【问题描述】:

我正在尝试在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);
}

【问题讨论】:

  • 哪一行引发了错误?
  • 页面切换后需要等待
  • 子页面是什么意思?您是否尝试在数据表中移动?顺便说一句,Ankur 是对的,加载页面和填充 DOM 需要几秒钟。同样取决于 col.click 触发的内容,如果页面在下一次循环开始时尚未完成更新,它也可能导致超时问题。您可以尝试投入一些等待或子循环来寻找元素!= null。没有更多细节,很难提供更多帮助。
  • 此代码与页面有关。 domiporta.pl/mieszkanie/…。这是一个房地产类型提供的列表。问题是 col.click();当我取消这条线时,一切都很好。但是这段代码是最重要的。 col.click() 在从报价中获取一些数据后进入报价(子页面),程序应该返回列表并进入下一个报价。但此时问题出现了——页面不再有效。

标签: java selenium selenium-webdriver webdriver staleelementreferenceexception


【解决方案1】:

好的,我明白了。

你必须明白,当你使用 '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);
}

【讨论】:

  • 导入 java.util.ArrayList;导入 java.util.List;导入 org.openqa.selenium.By;导入 org.openqa.selenium.WebDriver;导入 org.openqa.selenium.WebElement;导入 org.openqa.selenium.ie.InternetExplorerDriver; public class Domiporta{ public static void main(String[] args) throws InterruptedException { //Zmienne ogólne //Dane dla dolnośląskie.pi String startPage = "domiporta.pl/mieszkanie/…";
  • 第 2 部分// łącze się z Domiporta driver.get(startPage); List rows = driver.findElements(By.className("detail-card__heading")); List cols=new ArrayList(); for(int i=0;i
  • System.out.println("没有提供"+i++); }catch(org.openqa.selenium.StaleElementReferenceException ex) { System.out.println("Poszedł błąd" +i); } } System.out.println("Koniec"); } }
  • as user8537453 和@Ash as 你可以看到以这种方式工作的代码,我可以列出所有列表。问题是当我想点击报价时(代码第二部分的结尾 //col.click(); 我想进入每个报价,获取一些数据并返回但是当我进入报价时fo back driver.get(startPage) 是错误的。
猜你喜欢
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
  • 2018-04-08
  • 2014-06-06
  • 2014-10-05
  • 1970-01-01
相关资源
最近更新 更多