I am looking for a solution to the StaleElementReferenceException that arises when navigating back to a previous page with Selenium.
Here is a sample code to reproduce the error:
from selenium.webdriver import Chrome
from selenium.common.exceptions import NoSuchElementException
browser = Chrome()
browser.get('https://stackoverflow.com/questions/')
# Closing the pop-up for cookies
try:
browser.find_element_by_class_name('js-accept-cookies').click()
except NoSuchElementException:
pass
# Getting list of links on a StackOverflow page
links = browser.find_element_by_id('questions').find_elements_by_tag_name('a')
links[0].click()
# Going back
browser.back()
try:
browser.find_element_by_class_name('js-accept-cookies').click()
except NoSuchElementException:
pass
# Using the old links
links[1].click()
I understood the root cause from similar stackoverflow questions like this one Stale Element Reference Exception: How to solve?
However the proposed solution i.e. refetching the links everytime I am navigating back, does not suit me for performance reasons.
Is there any alternative ?
For example forcing the new page to open in a new tab so that I can therefore navigating between the two tabs ?
Any other solution is appreciated