list - 通过 selenium webdriver 单击第一个链接后,无法单击列表中保存的链接
问题描述
我正在尝试一一单击保存在本网站列表中的所有产品链接。第一个链接被点击但是,当页面导航回点击第二个链接时,我收到错误“StaleReferenceException”。我被打动了 - elementToBeClicked.click(); 我在互联网上搜索了解决此类错误的方法,但没有成功。请帮帮我。这是我的代码:
WebElement prodList = util.getdriver().findElement(By.id("atg_store_prodList"));
// Finding all links and saving in a list
List<WebElement> alllinks = prodList.findElements(By.xpath(".//div[@class='product-name']/a"));
System.out.println(alllinks);
for (int i = 0; i < alllinks.size(); i++) {
alllinks = prodList.findElements(By.xpath(".//div[@class='product-name']/a"));
System.out.println(alllinks.get(i));
WebElement elementToBeClicked = alllinks.get(i);
Thread.sleep(5000);
elementToBeClicked.click();
util.clickbyXpath(Constants.BOOTSIZE);
Thread.sleep(5000);
util.getdriver().findElement(By.id("atg_behavior_addItemToCart")).click();
if (util.getdriver().findElement(By.xpath("//a[contains(text(),'Continue Shopping')]"))
.isDisplayed()) {
util.getdriver().findElement(By.xpath("//a[contains(text(),'Continue Shopping')]"))
.click();
util.getdriver().navigate().back();
}
else {
util.getdriver().findElement(By.xpath("//a[@title='Checkout']")).click();
Select selectCountry = new Select(
}
}
解决方案
试试这个代码,它在我的最后工作:
driver.get("https://www.barneys.com/category/women/shoes/boots/N-po186i");
Thread.sleep(5000);
for(int i=0 ; i<100; i++) {
int attempts = 0;
while(attempts < 2) {
try {
List<WebElement> alllinks = driver.findElements(By.xpath("//div[@class='product-name']/a"));
alllinks.get(i).click();
break;
}
catch(StaleElementReferenceException e) {
System.err.println(e.getMessage());
}
attempts++;
}
Thread.sleep(5000);
// do your operation such as getting the detail of product or anything
System.out.println(driver.getTitle());
driver.navigate().back();
driver.navigate().refresh();
}
推荐阅读
- consul - 是否可以配置可以设置为关键的 Consul 健康检查,但在 TTL 之后默认为健康?
- java - Spring AntPathMatcher 行为
- javascript - 如何使用 addEventListener 在数组中导航?
- swift - 如何在 SwiftUI 的 ScrollView 中创建多行文本?
- java - 如何在 Jira 云中创建工作流
- delphi - 目标多字节代码页中不存在 Unicode 字符的映射:如何将 MemoryStream 转换为 String
- .net-core - 如何将“用户信息”传递给“HubConnectionBuilder()”
- broadleaf-commerce - 如何在 Broadleaf Admin 中创建自定义页面
- reactjs - 如何使用 rollup.js 优化 React 应用程序包的大小
- azure-devops - 如何从基于 git 标签而不是分支的构建中执行发布?