首页 > 解决方案 > 通过 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(

                                }
                            }

标签: listseleniumhyperlinkautomationwebdriver

解决方案


试试这个代码,它在我的最后工作:

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();
}

推荐阅读