我有一个下拉列表,我可以第一次按索引选择元素。当我尝试第二次选择元素时,它会抛出陈旧元素引用错误。我尝试使用 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.
最佳答案
当您之前找到的元素不再附加到 DOM(HTML 源代码)时,会发生
StaleElementReferenceException
。已更改,需要重新查找。元素已更改,因为您执行了 select
操作并且其值已更改。
解决方案:再次找到您的元素,如下所示:
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.
关于java - Selenium 网络驱动程序 : stale element reference: element is not attached to the page document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49063045/