元素是可单击的,但“未附加到页面文档”(StaleElementReferenceException)?

时间:2019-02-08 10:05:43

标签: python linux selenium

我试图单击一个按钮,但有时会收到Stale元素异常:

selenium.common.exceptions.StaleElementReferenceException:消息:陈旧元素引用:元素未附加到页面文档

即使我使用element_to_be_clickable预期条件在DOM中查找元素。当我的脚本在else语句中继续时,找到该元素,但是当我尝试单击按钮-BAM时,该元素未附加到页面文档中。到底是什么硒?!?!!?

我要查找的元素在新加载的页面中,即脚本中的上一个操作是单击按钮,然后将其重定向到我遇到上述问题的页面。

我感觉到python的硒很垃圾。否则,我在做什么错,ffs?重要说明,我不要引入任何隐式等待,例如time.sleep或hidden_​​wait!我希望我的代码比以前更灵活。

我找到了具有element_to_be_clickable预期条件的元素,但是当我尝试单击它时,硒(有时)崩溃,表示该元素实际上未连接到DOM。 ?!它通常发生在Google Chrome中!

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语句,我希望能够单击该按钮。

1 个答案:

答案 0 :(得分:0)

旧元素表示旧元素或不再可用的元素。如果DOM更改,则WebElement会过时。如果我们尝试与已停滞的元素进行交互,则将抛出StaleElementReferenceException。

尝试使用Fluent Wait,它将帮助您避免某些异常,例如StaleElementReferenceExcetion,NoSuchElementException等,

尝试以下代码:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import *

# Some driver initialization code goes here
xpath = "//i[@class='far fa-flag']"    
wait = WebDriverWait(driver, 60, poll_frequency=1, ignored_exceptions=[StaleElementReferenceException])
element = wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))
element.click()

如果您想避免其他一些异常,请在ignored_exceptions中添加,如下所示:

ignored_exceptions=[StaleElementReferenceException, NoSuchElementException]

希望对您有帮助...

相关问题