【发布时间】:2019-02-08 19:36:07
【问题描述】:
我正在尝试单击一个按钮,但有时会收到 Stale 元素异常:
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attach to the page document
即使我使用 element_to_be_clickable 预期条件来查找 DOM 中的元素。当我的脚本在 else 语句中继续时找到该元素,但是当我尝试单击按钮 - BAM 时,该元素未附加到页面文档。到底是什么,硒?!?!!?
我要查找的元素位于新加载的页面中,即脚本中的上一个操作是单击按钮,然后重定向到我遇到所描述问题的页面。
我觉得 python 的 selenium 是垃圾。否则,我做错了什么,ffs?重要说明,我不想引入任何隐式等待,例如 time.sleep 或implicitly_wait!我希望我的代码比这更灵活。
我找到了具有 element_to_be_clickable 预期条件的元素,但是当我尝试单击它时,selenium(有时)会崩溃,说该元素实际上没有附加到 DOM。 ?!它主要发生在谷歌浏览器中!
try: casesButton = WebDriverWait(driver,4).until(expc.element_to_be_clickable((By.XPATH, "//i[@class='far fa-flag']")))
except (TimeoutException, ElementNotVisibleException, NoSuchElementException): result = 0; reason = "Cases button not found"
else: casesButton.click()
崩溃消息:
casesButton.click()
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webelement.py", line 80, in click
self._execute(Command.CLICK_ELEMENT)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.6/dist-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=70.0.3538.77)
(Driver info: chromedriver=2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881),platform=Linux 4.15.0-36-generic x86_64)
考虑到我的代码进入了 else 语句,我希望能够点击按钮。
【问题讨论】: