Reputation: 568
Error Output:
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <span class="a-size-medium a-color-base a-text-normal"> 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 refreshed
I was trying to do the following with selenium:
However it failed at click()
Code:
def experiment2():
browser = webdriver.Firefox()
browser.get("https://www.amazon.com/")
searchelement = browser.find_element_by_css_selector("#twotabsearchtextbox")
searchelement.send_keys('automate the boring stuff with python')
searchelement.submit()
time.sleep(5)
elements = browser.find_elements_by_css_selector("span.a-color-base.a-text-normal")
for element in elements:
element.click()
try:
element = browser.find_element_by_css_selector("span.a-size-medium:nth-child(2)")
print(element.text)
except:
browser.back()
time.sleep(2)
continue
browser.back()
time.sleep(2)
What could have caused this issue?
Upvotes: 0
Views: 383
Reputation: 33384
Since you are using driver.back() it refreshed the page and the elements you have captured it is no longer attached to the page.you need reassigned the elements again.
Try below code
def experiment2():
browser = webdriver.Firefox()
browser.get("https://www.amazon.com/")
searchelement = browser.find_element_by_css_selector("#twotabsearchtextbox")
searchelement.send_keys('automate the boring stuff with python')
searchelement.submit()
time.sleep(5)
elements = browser.find_elements_by_css_selector("span.a-color-base.a-text-normal")
for element in range(len(elements)):
elements = browser.find_elements_by_css_selector("span.a-color-base.a-text-normal")
elements[element].click()
try:
element = browser.find_element_by_css_selector("span.a-size-medium:nth-child(2)")
print(element.text)
except:
browser.back()
time.sleep(2)
continue
browser.back()
time.sleep(2)
Upvotes: 2