📌  相关文章
📜  selenium.common.exceptions.ElementNotInteractableException:消息:元素不可交互 - Python (1)

📅  最后修改于: 2023-12-03 15:20:04.428000             🧑  作者: Mango

关于selenium.common.exceptions.ElementNotInteractableException

selenium.common.exceptions.ElementNotInteractableException 是一个 Selenium 的异常类型,它通常在操作不能进行交互的元素时抛出。例如,尝试在一个不可编辑的输入框中输入文本时,或者尝试点击一个被禁用的按钮时,都会引发这个异常。

在 Python 中使用 Selenium 进行自动化测试时,遇到这个异常可能是比较常见的。一般来说,我们可以使用一些方法来解决这个问题,比如等待元素可交互再执行操作、使用 JavaScript 脚本执行操作等等。

以下是一个例子,展示了如何捕获这个异常并使用等待来解决:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import ElementNotInteractableException

# 等待元素可点击再执行操作
try:
    button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, "my-button"))
    )
    button.click()
except ElementNotInteractableException as e:
    print("Encountered an element not interactable error:", e)

以上代码使用了显式等待,等待了 10 秒钟以内按钮可点击再执行点击操作。如果元素不可交互,则捕获异常并输出错误信息。

当然,除了以上方法,解决这个问题的方式也有很多,具体可以根据实际情况选择适合自己的方法。

希望这篇介绍能够帮助到需要用 Selenium 进行自动化测试的 Python 开发者们!