Selenium:StaleElementReferenceException

时间:2016-03-08 06:29:13

标签: java selenium-webdriver

我已经研究了这个错误一段时间了,尝试了很多东西,似乎什么都没有用......

        while(!driver.findElements(By.className("next")).isEmpty()) { 
            //elements = driver.findElements(By.xpath("//a[@class='name']"));
            elements = findDynamicElements("//a[@class='name']");
            for (WebElement e : elements) {
                userName = e.getText(); //<--EXCEPTION HERE
                check_visitor_profile(userName);//<--WE LEAVE THE PAGE HERE
                Thread.sleep(3000); //<--NO TRY/CATCH BLOCK FOR READABILITY
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                elements = findDynamicElements("//a[@class='name']");

            }
            driver.findElement(By.xpath("VisitsNext")).click();
        }       



protected List<WebElement> findDynamicElements(String path) {
        List<WebElement> result;
        String xPath = path;
        new WebDriverWait(driver, 25).until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(xPath)));
        //new WebDriverWait(driver, 25).until(elementIdentified(By.id(path)));

        try {
            result = driver.findElements(By.xpath(xPath));
            return result;
        }
        catch(WebDriverException e) {
            return null;
        }
    );
    }

我的代码在分配userName的for循环的第一行开始。我在这个论坛上看到你应该使用&#39; presenceOfElementLocated&#39;并明确地等待元素返回,但这也不起作用。我使用了#OvoutOfAllElementsLocatedBy&#39;对于列表,但我有一个方法,使用&#39; presenceOfElementLocated&#39;哪个也不起作用。

我知道像Thread.sleep这样的东西,而且隐含的等待线在这一点上可能是不必要的,但是我确实尝试了所有的东西而且它没有用......

发生错误是因为我打电话给check_visitor_profile&#39;它离开页面 - 当它返回时,元素不合适,所以我必须再次找到它们。我做了但它仍然抛出异常。

任何想法?

感谢。

2 个答案:

答案 0 :(得分:1)

可能会出现此问题,因为您正在循环中间更改elements。即使没有StaleElementReferenceException,它也会给您带来麻烦。使用for循环代替for each循环

elements = findDynamicElements("//a[@class='name']");
int size = elements.size();
for (int i = 0 ; i < size ; ++i) {
    elements = findDynamicElements("//a[@class='name']");
    userName = elements.get(i).getText();
    check_visitor_profile(userName);
}

答案 1 :(得分:0)

明确处理异常,因为元素不再附加到DOM或在您调用&#34; check_visitor_profile&#34;

的那一刻发生了变化

请参阅以下链接可能有帮助

            catch(StateElementException e){
             System.out.println("StaleElement dealt with since you successfully left page "); 
              }

see picture of senario