Selenium – Stale Element Reference Exception when using element.click()

Question:

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:

  1. go to amazon
  2. search automate the boring stuff with python
  3. click the first product title
  4. if the price tag element, is on the product site, print it, and go back to the previous page
  5. if it not available, go back to the previous page
  6. go to the next product title and repeat from step 4

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?

Asked By: DeltaHaxor

||

Answers:

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)
Answered By: KunduK