'Stale element exception - Element does not exist in cache while I am testing the anchor tags

I am testing all the anchor tags on a page in mobile view using Java selenium. The process is that we are clicking on each anchor link one by one. I have taken all the anchor tags in a list and iterating it one by one using a for loop. Once I click the first anchor link, it navigates me to another url. After verifying the url, it should go back to previous page using webDriver.navigate().back(). Now when the loop picks up the next anchor tag web element from the list, it gives this exception-

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document Element: [[ChromeDriver: chrome on WINDOWS (67f684a79823c7205d56a9420aa761f2)] -> css selector: .cmp-globalsite-articletext a]

I have also used @CacheLookup to the list of web elements having the anchor tag css selector, but still it gives the error. This is how I have defined the css selector in my mobile class.

@CacheLookup
@FindBy(css = ".cmp-globalsite-articletext a")
List<WebElement> articleTextAnchorLinks;

Please note that I couldn't open the pages in a new tab in mobile view so the only option here is to click on each anchor link, do the testing and navigate back to the original url, then click on second anchor link and so on.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source