selenium-webdriverwebdriverstaleelementreferenceexception

is there a way to handle stale Element in selenium?


i was navigating to a page which had a list of menu in that page and i wanted to check if i can click on all the menu and get expected outcome, since some of the menu option navigated me to different screen ; i navigated back to original screen to check remaining options but after first navigation my elements are becoming stale

for (int i = 0; i < menu.size(); i++) {
        
        String menuName = menu.get(i).getText();

        if (menuName.contains("Home")) {
            
            menu.get(i).click();
            
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
            
            String pageDetails = driver.getCurrentUrl();
            
            
            driver.navigate().back();
            driver.navigate().refresh();
            
            
        }
    }

Solution

  • Well, the behaviour is completely correct from testing perspective. (Really, who knows what's happened to the original page while you were "outside"? Elements need to be refreshed.)

    Some frameworks (like Selenide) have methods that use dynamic refresh of elements during iteration (see asDynamicIterable) but it is Not Recommended.

    Try to open your menu items in other tab and verify it after you have opened them all. Or work with other windows tabs not leaving current one. See this article