我正在尝试逐个点击此website中列表中保存的所有产品链接。第一个链接被点击,但是当页面被导航回来点击第二个链接时,我收到错误" 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(
}
}
答案 0 :(得分:0)
当您点击该链接时,它会触发导航,您将转到新页面。一旦发生新的导航,DOM中的所有旧元素都将变得陈旧且不再可用(您不再在该页面上)。您必须再次导航回原始页面并重新加载它以获得带有新元素的新DOM。
TLDR:触发导航刷新DOM,无法再从旧DOM访问元素。这就是硒的作用方式。
答案 1 :(得分:0)
试试这段代码,它在我的最后工作:
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();
}