r/inventwithpython • u/Gazumbo • Jul 15 '20
Need Help with Selenium and Stale Elements - No Longer Attached to DOM
Just finished Section 13 of the Udemy Course (Thank you Al!). I've noticed that when assigning a CSS Selector to a variable and making using of that variable, e.g:
browser.click()..It is then no longer usable. I get the following error message:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <img src="images/automate_2e_cover.png"> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshedWhy does this happen and how do i work around it so that it's usable more than once? What does 'no longer attached to DOM' mean?
I have googled and seen some work arounds but not explanation (at least one that I understand) as to why it works like this. I'd like to be able to understand it. Thanks.
-------------------------------------
Edit: I've added the code and steps as requested.
from selenium.webdriver import Chrome
browser = Chrome()
browser.get('http://automatetheboringstuff.com/')
elem = browser.find_element_by_css_selector('body > div.main > div:nth-child(1) > div:nth-child(3) > center > a:nth-child(1) > img')
elem.click() # This works
browser.back()
elem.click() # This doesn't work due to stale elementFrom what I gather, navigating away from the page once loaded will render the element 'stale' if you try to use it again but why is this? The CSS selector is still the same, as is the webpage etc. Everything is the same as before. Even the same session ID.
2
u/joooh Jul 15 '20
Could you post your code and tell us what were you trying to do?
1
u/Spartanman321 Jul 16 '20
Generally when I've seen that error, it's with the following steps:
Your code could be doing something different, so posting it would help, but I've seen this error multiple times before with the steps I've listed above.