切换窗口在 selenium webelement java 中不起作用



我有webelements列表,在foreach循环中迭代这个列表,在点击webelement的循环中,从一个屏幕切换到第二个屏幕,在第二个屏幕中,我有后退按钮,我做完工作后我按下后退按钮,然后再次回到第一个屏幕,里面有那个webelements列表。整个场景仅适用于第一次迭代,但在第二次迭代中出现这样的异常,

"org.openqa.selenium.StaleElementReferenceException:在缓存中找不到元素 - 也许页面在查找后已更改 命令持续时间或超时:50.13 秒"

以下是我的代码,

  try {           /**
       * In this scenario i am iterating through webelementlist, in first iteration i have clicked first 
       * webelement, then fetching some values from second screen after doing my work returning back
       * to the first one. 
       */             List<WebElement> elementList = driver.findElements(By.className("classname"));
      for(WebElement webElement: elementList){
          webElement.click();
          //fetching some values
          String str = driver.findElement(By.className("classname")).getText();
          System.out.println("Value : "+str);
          //returning back to the first page
          driver.findElement(By.xpath(".//*[@id='pane']/div/div[1]/div/button")).click();
      }       } catch (Exception e) {             e.printStackTrace();        }

为此工作了很长时间,但甚至没有得到任何解决方案。

当您离开页面或刷新 DOM 时,驱动程序会丢失之前找到的所有 WebElements。您需要在每次迭代时重新定位列表

int size = 1;
for (int i = 0 ; i < size ; ++i) {
    List<WebElement> elementList = driver.findElements(By.className("classname"));
    elementList.get(i).click(); // click the element by index
    size = elementList.size();  // change "size" to the list size
    //fetching some values
    String str = driver.findElement(By.className("classname")).getText();
    System.out.println("Value : "+str);
    //returning back to the first page
    driver.findElement(By.xpath(".//[@id='pane']/div/div[1]/div/button")).click();
}
    "org.openqa.selenium.StaleElementReferenceException can occur
 any time, it should be handled and the execution should continue...
    int count=0;
    while(count<4)
    {
    try{
    int size = 1;
    for (int i = 0 ; i < size ; ++i) {
        List<WebElement> elementList = driver.findElements(By.className("classname"));
        elementList.get(i).click(); // click the element by index
        size = elementList.size();  // change "size" to the list size
        //fetching some values
        String str = driver.findElement(By.className("classname")).getText();
        System.out.println("Value : "+str);
        //returning back to the first page
        driver.findElement(By.xpath(".//[@id='pane']/div/div[1]/div/button")).click();
    } } count=count+4;
     catch(StaleElementReferenceException e)
    {
    System.out.println("recover from exception");
    count=count+1; continue;
    }
}

最新更新