切换窗口不在selenium webelement java中工作

时间:2016-04-28 06:55:54

标签: java selenium webdriver

我有webelements列表,在foreach循环中迭代此列表,在点击webelement的循环中,从一个屏幕切换到第二个屏幕,在第二个屏幕中,我在完成工作后有后退按钮我按下后退按钮和再次回到第一个屏幕,其中包含了这个列表。整个场景仅适用于第一次迭代,但在第二次迭代中获得此类异常,

  

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

长时间工作,但即使没有得到任何解决方案。

2 个答案:

答案 0 :(得分:1)

当您离开页面或刷新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();
}

答案 1 :(得分:1)

    "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;
    }
}