Two reasons for Stale element
An element that is found on a web page referenced as a WebElement in WebDriver then the DOM changes (probably due to JavaScript functions) that WebElement goes stale.
The element has been deleted entirely.
When you try to interact with the staled WebElement[any above case], the StaleElementException is thrown.
Solutions to resolve them:
- Storing locators to your elements instead of references
DON'T
driver = webdriver.Firefox();
driver.get("http://www.github.com");
search_input = driver.find_element_by_name('q');
search_input.send_keys('hello world\n'); // Page contents refresh after typing in search results.
time.sleep(5);
search_input.send_keys('hello frank\n'); // StaleElementReferenceException
Do
driver = webdriver.Firefox();
driver.get("http://www.github.com");
search_input = lambda: driver.find_element_by_name('q');
search_input().send_keys('hello world\n');
time.sleep(5);
search_input().send_keys('hello frank\n') // no stale element exception
- Leverage hooks in the JS libraries used
# Using Jquery queue to get animation queue length.
animationQueueIs = """
return $.queue( $("#%s")[0], "fx").length;
""" % element_id
wait_until(lambda: self.driver.execute_script(animationQueueIs)==0)
- Moving your actions into JavaScript injection
self.driver.execute_script("$(\"li:contains('Narendra')\").click()");
- Proactively wait for the element to go stale
# Wait till the element goes stale, this means the list has updated
wait_until(lambda: is_element_stale(old_link_reference))
This solution, which worked for me, I have mentioned here if you have any additional scenario, which worked for you then comment below or contact me so that we can add into solution list