首页 > 解决方案 > Selenium Python 无法单击按钮:ElementNotInteractable 或 StaleElementReferenceException

问题描述

我正在尝试自动化 MS Teams 并且无法通过登录,因为在输入密码后我在单击登录按钮时遇到问题。

如果我尝试:

button = driver.find_element_by_xpath('//*[@id="idSIButton9"]')
button.click()

我得到:

ElementNotInteractableException:消息:元素不可交互。

如果我尝试使用 Action Chains 方法解决它(这似乎已经为很多人解决了许多类似的问题):

button = driver.find_element_by_xpath('//*[@id="idSIButton9"]')
driver.implicitly_wait(10)
ActionChains(driver).move_to_element(button).click(button).perform()

我得到:

StaleElementReferenceException:消息:过时的元素引用:元素未附加到页面文档

值得一提的是,手动登录时,我可以在输入密码后按回车键通过此阶段,但使用发送密钥方法也无法成功。

标签: pythonseleniumselenium-webdriver

解决方案


您尝试使用 XPath 定位的元素driver.find_element_by_xpath('//*[@id="idSIButton9"]')可能是前一个屏幕和新屏幕的一部分,因此驱动程序可能正在引用作为前一个屏幕一部分的元素,因此您会收到 StaleElementReferenceException。

解决这个问题的最简单方法是,您可以driver.refresh()在上述 xpath 之前添加,这将使用新元素加载页面和 DOM。

否则,您可以使用不同的定位器策略来唯一标识该元素。


推荐阅读