当前位置: 首页 > 知识库问答 >
问题:

Selenium webdriver:陈旧元素引用:元素未附加到页面文档

海嘉赐
2023-03-14

我有一个下拉列表,我第一次能够按索引选择元素。当我第二次尝试选择元素时,它会抛出陈旧的元素引用错误。我尝试了try catch block,显式等待,但没有任何效果。

WebElement drop = driver.findElement(By.cssSelector("#ctl00_mainPanel_MainPanel1_SearchStop1_DropDownRoute"));

Select sel_drop = new Select(drop);
List<WebElement> drop_count = sel_drop.getOptions();
int drop_size = drop_count.size();
System.out.println("size of drop down" + drop_size);
sel_drop.selectByIndex(1);


JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(250,0)", "");

sel_drop.selectByIndex(10);//this line is causing error-- when I am trying to select element from dropbox for second time.

共有2个答案

顾高翰
2023-03-14

在没有相关的超文本标记语言的情况下,很难猜测为什么您在尝试选择第二个选项时会看到StaleElementRe传染ceException,但在这一点上值得一提的是,有效的usecase将包含根据超文本标记语言DOM仅选择单个元素的步骤,并继续执行其他步骤。因此,根据您的代码块,如果第一个selectByIndex的选择有效,则可以开始了。

WebElement drop = driver.findElement(By.cssSelector("#ctl00_mainPanel_MainPanel1_SearchStop1_DropDownRoute"));
Select sel_drop = new Select(drop);
List<WebElement> drop_count = sel_drop.getOptions();
int drop_size = drop_count.size();
System.out.println("size of drop down" + drop_size);
sel_drop.selectByIndex(1);

如果选择第一个<代码>

在这里,您可以找到关于StaleElementReferenceException的详细讨论

龚德本
2023-03-14

当您以前找到的元素不再附加到DOM(HTML源)时,会发生StaleElementReferenceException。它已被更改,需要重新找到。元素已更改,因为您执行了选择操作,并且其值已更改。

解决方案:按如下方式再次查找元素:

WebElement drop = driver.findElement(By.cssSelector("#ctl00_mainPanel_MainPanel1_SearchStop1_DropDownRoute"));

Select sel_drop = new Select(drop);
List<WebElement> drop_count = sel_drop.getOptions();
int drop_size = drop_count.size();
System.out.println("size of drop down" + drop_size);
sel_drop.selectByIndex(1);

//below lines are crucial
drop = driver.findElement(By.cssSelector("#ctl00_mainPanel_MainPanel1_SearchStop1_DropDownRoute"));
sel_drop = new Select(drop);

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(250,0)", "");

sel_drop.selectByIndex(10);//this line is causing error-- when I am trying to select element from dropbox for second time.
 类似资料:
  • 我有一个客户想要从网站上抓取一些信息。循环第一次工作,但第二次发生错误。有什么帮助吗?我也不建议去实际的网站,它很粗略。 代码: 错误: selenium.common.exceptions.StaleElementReferenceException:消息:陈旧的元素引用:元素未附加到页面文档 完全终端回溯: 完成回溯(最近的最后一次调用):文件"c:\用户\Heage\Coding\自由职业\

  • 问题内容: 在我的C#应用​​程序中使用Selenium Web驱动程序时,出现以下错误: OpenQA.Selenium.StaleElementReferenceException:陈旧元素引用:元素未附加到页面文档 在此代码中: 错误行在中,但这是在XPath之前指定的相同链接中成功执行但在最后一次尝试中失败的过程!那么这个错误是什么意思以及如何解决呢? 问题答案: 这意味着在页面中更改的元

  • 我正在使用C#和Selenium Chromedriver来做一个测试项目,以抓取谷歌地图。 在到达第二个循环之前,它运行良好: 返回: OpenQA. Selenium.过时元素引用:元素未附加到页面文档 这是我所有的代码: 任何帮助将不胜感激!

  • 我得到了这个错误,当我试图点击一个下拉ID: 我想用这个代码: 有没有什么方法可以防止无限循环,或者更好的方法在我得到这个异常后点击id?

  • 我正在构建一个刮网站的c#应用程序。我认为这个问题是因为页面在一次又一次提交表单后被重新加载而导致的。我必须从选择列表中选择一个选项,然后按回车键,等待页面重新加载新结果。但是重新加载后会导致此错误; 我的代码是这样的; 我也尝试过类似的东西; 时间不多了,我有个例外,时间不多了。

  • 这是HTML结构如下所示 错误跟踪为: