所以我的代码试图通过一个链接列表(所有链接的可见文本都是“年度”),然后,当在新网页上时,在年份的下拉列表中迭代大约 20 年并下载一个数据集每年。所以有两个循环。我的代码陷入了年循环 - 也就是说,对于相同的“年度”,它在 2 年后出现过时元素错误。
我正在使用 chrome,这是我的代码的相关部分:
Links = browser.find_elements_by_link_text("Annual")
for link in Links:
link.click()
time.sleep(20)
browser.switch_to_window(browser.window_handles[-1])
select = Select(browser.find_element_by_xpath('//select[@name="year"]'))
options = select.options
for index in range(0, len(options)):
select.select_by_index(index)
time.sleep(10)
excelbutton = browser.find_element_by_xpath('//a[img[@title="Download as Excel"]]').click()
错误如下:selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attach to the page document
将不胜感激任何帮助!我试图通过答案,但由于我正在使用 2 个循环,其中一个工作正常,因为它可以工作长达 2 年,所以我无法弄清楚。
更新:完整的错误信息:
Traceback (most recent call last):
File "abc", line 56, in <module>
select.select_by_index(index)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/support/select.py", line 99, in select_by_index
for opt in self.options:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/support/select.py", line 47, in options
return self._el.find_elements(By.TAG_NAME, 'option')
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 527, in find_elements
{"using": by, "value": value})['value']
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 493, in _execute
return self._parent.execute(command, params)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 249, in execute
self.error_handler.check_response(response)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 193, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=67.0.3396.99)
(Driver info: chromedriver=2.40.565386 (45a059dc425e08165f9a10324bd1380cc13ca363),platform=Mac OS X 10.11.6 x86_64)