Getting a stale element exception (Selenium - Java)
I am using Selenium via Java.
I am running into a stale element exception and I can't seem to identify the issue.
I am interacting with a carousel (see image below). I have placed all the vehicles, in the carousel, into a list and I am trying to get the text back from each web element in the list. The list contains eight elements. When my code interacts with the last page of the carousel (in this case the sixth element in the list) a stale element exception gets thrown.
Here is the code where I placed all the vehicles in the carousel in a list:
List vehiclesInCarousel = driver.findElements(By.cssSelector("div[data-qaid='cntnr-frntlnlstng-carousel'] ul[class='slider-list'] li[class='slider-slide']"));
irl last edited by
Two reasons for Stale element
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
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.
search_input.send_keys('hello frank\n'); // StaleElementReferenceException
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"), "fx").length; """ % element_id wait_until(lambda: self.driver.execute_script(animationQueueIs)==0)
- 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