[英]Selenium Webdriver - Stale element exception when clicking on multiple dropdowns while HTML DOM doesn't change
[英]Selenium Webdriver - Stale element exception when clicking on multiple dropdowns in a for loop
我写下了一段代码,我需要在其中自动生成一个包含 4 个可用选项的下拉菜单。 我正在使用 for 循环来检查下拉列表中的值,然后单击下拉列表中存在的每个选项并验证应用程序是否根据下拉列表的选择返回正确的结果。
发现错误:但是,在单击一个选项后,它从 for 循环中出来并且直到下拉列表的大小才执行并返回 state 元素异常。 这里我附上代码:
Select select = new Select(hp.sort());
List<WebElement> values = select.getOptions();
for (int i = 0; i < values.size(); i++) {
System.out.println(values.get(i).getText());
if (values.get(i).getText().equals("Name (A to Z)")) {
}
else if (values.get(i).getText().equals("Name (Z to A)")) {
select.selectByVisibleText(values.get(i).getText());
driver.navigate().refresh();
}
else if (values.get(i).getText().equals("Price (low to high)")) {
select.selectByVisibleText(values.get(i).getText());
}
else if (values.get(i).getText().equals("Price (high to low)")){
select.selectByVisibleText(values.get(i).getText());
}
}
StaleElementReferenceException
简而言之:
Selenium 具有客户端-服务器架构。
当您将WebElement/List<WebElement>
存储在代码中的某个变量中时,所有元素都是对服务器端真实元素的某种引用。 所有的元素都像缓存的。
因此,如果元素的结构将被更改,则此引用可能很容易被破坏。 重现这一点的最简单方法:
WebElement myButton = driver.findElement(...); // myButton keeps the reference to the page element
driver.navigate().refresh(); // page structure changed, all existing references became broken
myButton.click(); // this will throw StaleElementReferenceException
跟踪任何页面结构更新并显式刷新元素引用。
WebElement myButton = driver.findElement(...); // element reference created
...
driver.navigate().refresh(); // page structure changed, all existing references became broken
myButton = driver.findElement(...); // refresh the reference
myButton.click();
另见
https://developer.mozilla.org/en-US/docs/Web/WebDriver/Errors/StaleElementReference
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.