Stale Element Reference error in Selenium

前端 未结 2 665
无人及你
无人及你 2020-12-22 12:54

I am getting an error while running my selenium tests

Exception in thread \"main\" 
org.openqa.selenium.StaleElementReferenceException: stale element 
refere         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-22 13:34

    You should spend some time reading about and understanding what a StaleElementReferenceException is. It is important to understand what causes it and what to do to avoid it.

    In this case, you are scraping the page and loading category with elements off of Page 1. You then click some link that takes you to page 2. At that point, all the references in category are stale but an exception isn't thrown yet because you haven't accessed any of the variables yet. You then use .back() to return to Page 1 and attempt to do something with category and get the exception.

    To avoid this, you need to rescrape the elements into category on Page 1 after you use .back() from another page. One way is what I've written below. The page is scraped at the bottom of each loop.

    List category = driver.findElements(By.className("a2s-skill-block"));
    for (int i = 0; i < category.size(); i++)
    {
        category.get(i).click();
        // sleeps are a bad practice, use WebDriverWait instead
        driver.navigate().back();
        driver.findElement(By.id("iApps")).click();
        // sleeps are a bad practice, use WebDriverWait instead
        category = driver.findElements(By.className("a2s-skill-block"));
    }
    

提交回复
热议问题