【问题标题】:I am unable to visit the list of WebElements one by one using Selenium WebDriver我无法使用 Selenium WebDriver 逐一访问 WebElements 列表
【发布时间】:2017-04-15 08:59:42
【问题描述】:

我想在亚马逊上搜索一个主题,然后在给定的书籍列表中逐一执行特定操作。我做了以下事情:

    WebDriver driver= new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.amazon.com");
        driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Operating System Books");
        driver.findElement(By.className("nav-input")).click();
        links = driver.findElements(By.className("s-access-detail-page")); //try to cache this
        for(WebElement link : links) {
              //System.out.println(String.format(link.getAttribute("href"))); //prints
              link.click();
              //extract reviews and one by one forward to semantic analysis 
              driver.navigate().back();
          }
        }

但是,此链接转到第一个链接,然后返回列表页面。然后程序终止并出现以下错误: 线程“main”中的异常 org.openqa.selenium.StaleElementReferenceException:过时的元素引用:元素未附加到页面文档

【问题讨论】:

  • 出现此异常是完全正常的:StaleElement 表示您尝试引用的元素不再位于活动浏览器窗口中。考虑到您已经导航到其他页面,然后又导航回来,上一页中的任何元素都不应再处于活动状态。您要么必须重新搜索或在新窗口中打开链接,因此您的原始窗口在另一个浏览器选项卡中仍然完好无损。

标签: java selenium selenium-webdriver


【解决方案1】:

StaleElementReferenceExceptionwebElement 不再附加到 DOM 时,这通常发生在您离开网页然后导航回原始页面后尝试使用之前存储或捕获的 WebElements .

为了避免此异常,您需要再次识别先前捕获的元素,在您的情况下,您的代码应如下所示:

List <WebElement>links = driver.findElements(By.className("s-access-detail-page")); //try to cache this

        for(int i=0; i< links.size(); i++) {

             List <WebElement> refLinks = driver.findElements(By.className("s-access-detail-page"));

             refLinks.get(i).click();

             driver.navigate().back();

        }

【讨论】:

    【解决方案2】:

    错误,因为:您所引用的元素不再存在于活动页面中。试试这个代码:

         public static void main(String[] args) {
          WebDriver driver= new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://www.amazon.com");
        driver.findElement(By.id("twotabsearchtextbox")).sendKeys(
                "Operating System Books");
        driver.findElement(By.className("nav-input")).click();
        List<WebElement> links = driver.findElements(By
                .className("s-access-detail-page"));
    
        for (int i = 0; i < links.size(); i++) {
    
            List<WebElement> allLink = driver.findElements(By
                    .className("s-access-detail-page"));
    
            allLink.get(i).click();
    
    
    
            driver.navigate().back();
    
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2021-04-28
      • 2013-09-01
      • 1970-01-01
      • 2022-12-14
      • 2021-03-02
      • 1970-01-01
      相关资源
      最近更新 更多