So I am looping through a bunch of webpages. And currently the webpages all have the same structure with a back button and a forwards button (//span/a)[2]
. For some reason I can loop through the first page (and sometimes the second page). However I continue to get a StaleElementReferenceException
.
Here is the related code:
for x in range(0,5):
print 'page %d' %(x)
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "(//span/a)[2]"))
)
listItems = driver.find_elements_by_xpath("//td[@class='CourseCode']/a")
for element in listItems:
elementText = element.text
print(elementText)
writeFile.write(element.text + '\n')
driver.find_element_by_xpath("(//span/a)[2]").click()
In particular here is the stack trace:
Traceback (most recent call last):
File "getList.py", line 21, in lookup
addListItems(driver, courseCodeFile)
File "getList.py", line 44, in addListItems
elementText = element.text
File "/home/francisco/.local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 73, in text
return self._execute(Command.GET_ELEMENT_TEXT)['value']
File "/home/francisco/.local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 494, in _execute
return self._parent.execute(command, params)
File "/home/francisco/.local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "/home/francisco/.local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
StaleElementReferenceException: Message: The element reference is stale. Either the element is no longer attached to the DOM or the page has been refreshed.
I've tried a bunch to no avail. The weird thing is, if not looping through I was able to get the function to work properly for two pages.
Of note prior to the RTE, it would print the text of the first 2-3 elements of listItems
that were obtained in the previous page.