代码之家  ›  专栏  ›  技术社区  ›  Ishita Shah Y_Sh

我们可以在执行foreach循环时遍历另一页吗?

  •  3
  • Ishita Shah Y_Sh  · 技术社区  · 7 年前

    页面上有表格,我需要逐行检索信息。这是每个人的处理方式。在同一页上执行检索信息工作正常。


    到目前为止,我正在为每个循环处理它,并得到StaleElementReferenceException,这是正确的,因为webElement失去了它的实际 ListElement<WebElement>

    List<WebElement> findList = driver.findElements(By.xpath("//a[@class='*****']));
    
        for (WebElement webElement : findList) {
         ...
        //detail page is access by clicking webElement
        webElement.click();
    
        findList = driver.findElements(By.xpath("//a[@class='*****']));
        }
    

    如果有什么办法,请建议。谢谢。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Ishita Shah Y_Sh    7 年前

    List<WebElement> findList = driver.findElements(By.xpath("//a[@class='*****']));
    for(int i = 1 ; i<=findList.size() ; i++){
    
       driver.findElement(By.xpath("(//a[@class='***'])[" + i + "]")).click();
       // extract some data from next page which is invoked by clicking on Test1 hyperlink.
    }  
    

    每次你在寻找 //a[@class='***'][i] web元素i,从1开始到结束。

    P、 S:您需要在devtool中检查这个 //a[@class='***'][1] ,是否表示 是否超链接。

        2
  •  0
  •   Sers    7 年前

    尝试收集URL以详细说明所有页面,然后打开它们。

        3
  •  0
  •   Nish26    7 年前

    我可以想到两种情况:

    1. 单击链接(例如Test1)将打开一个新选项卡:

      • 在这种情况下,您只需切换到循环中的新选项卡,在此选项卡上完成操作,最后关闭第二个选项卡/切换到第一个选项卡,然后继续下一个项目。这也不应该导致StaleElementException。
      • 对于循环的每次迭代,单击目标链接,在新页上执行一些操作。在继续下一次迭代之前,再次导航到包含表的页,并再次查找所有行元素。现在,对于下一个迭代,您不会得到StaleElementException。您将希望使用for循环,以便可以在外部维护索引,而不是foreach变量。

    我建议使用第一个选项,因为这样会更干净,您可以在链接上执行shift+click,例如Test1,以强制在新选项卡中打开它,而不是在同一页中重定向。您可以使用“