Python Forum

Full Version: Error: StaleElementReferenceException
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Can somebody tell me why I keep getting a StaleElementReferenceException. Im doing a simple script that navigates to a page. Grabs the links and puts them into a list. Then navigates to each one of those links. It navigates to the first list item then I get the error.

The element reference of <a href="https://www.famousgraphicdesigners.org/alan-aldridge"> 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

Thanks in advance.

from selenium import webdriver

driver = webdriver.Firefox()

driver.get("https://www.famousgraphicdesigners.org/")

links = driver.find_elements_by_xpath('//*[@id="pages-2"]/div/ul/li/a')
links_total = len(links)
print("Found", links_total, "total links.\n")

for i in links:
	driver.get(i.get_attribute('href'))

driver.quit()
As you can see, I find the elements first than put it into a list. Than I go to the loop and try to navigate through the list of links. But it seems like the list clears when I navigate to a different page if that makes sense.
So I couldnt find a way to use the get_attribute without using it in a loop. So what I did was I looped the original list with the get_attribute and put it into a second list. Then looped through the 2nd list to navigate to each item on list.

from selenium import webdriver

driver = webdriver.Firefox()

driver.get("https://www.famousgraphicdesigners.org/")

links = driver.find_elements_by_xpath('//*[@id="pages-2"]/div/ul/li/a')
links_total = len(links)
print("Found", links_total, "total links.\n")

#Put elements with attribute into second list (links2)
links_total = len(links)
for i in links:
	links2.append(i.get_attribute('href'))

#Navigates to each link in list (list2)
for i in range(len(links2)):
	driver.get(links2[i])

driver.quit()