我正在尝试使用Selenium读取下拉菜单中元素的文本,但是当我使用“ element.text”时,我得到了一个过时的元素异常。 这是我的代码:
list_options = driver.find_elements_by_class_name("select2 results__option")
for l in list_options:
if l.text == "DOI":
l.click()
这是我收到的错误消息:
if l.text == "DOI":
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- packages/selenium/webdriver/remote/webelement.py", line 76, in text
return self._execute(Command.GET_ELEMENT_TEXT)['value']
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, 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=75.0.3770.80)
(Driver info: chromedriver=74.0.3729.6
(255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.1 x86_64)
我是Selenium的新手,将为您提供任何帮助。谢谢!
答案 0 :(得分:0)
单击该项目时,页面将刷新,并且您引用的元素(存储在变量中)是陈旧的。页面刷新更改的方式使得您存储的确切元素不再在页面上。为了解决这个问题,您需要在for循环中重新分配下拉列表。
尝试以下代码。
list_options = driver.find_elements_by_css_selector('.select2.results__option')
for l in range(len(list_options)):
new_list_options = driver.find_elements_by_css_selector('.select2.results__option')
if new_list_options[l].text == "DOI":
new_list_options[l].click()