【问题标题】:python selenium can't interact with input element? [duplicate]python selenium 不能与输入元素交互? [复制]
【发布时间】:2020-03-25 09:33:35
【问题描述】:

我正在尝试将我的名字放在输入字段中。 selenium 似乎是一件简单的事情,但我无法弄清楚我做错了什么。

name = driver.find_element_by_xpath('//input[@id="signUpName16"]')
name.send_keys('Josh')

我知道驱动程序可以正常工作,因为我已经能够单击其他元素。我知道 xpath 是正确的,因为我从 chrome 检查器中复制了它。我得到的错误是

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

我看到有人说要尝试单击或清除元素,所以我也尝试过,但仍然失败。

name = driver.find_element_by_xpath('//input[@id="signUpName16"]')
name.click()
name.send_keys('Josh')

为 name.click() 行产生这个

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

【问题讨论】:

  • 用相关的 HTML 更新问题

标签: python python-3.x selenium


【解决方案1】:

这里可能会出现一些不同的问题。如果input 未完全加载,那么如果您在准备好之前尝试send_keys,它将抛出此异常。我们可以在 input 元素上调用 WebDriverWait 以确保在向其发送密钥之前它已完全加载:

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


input = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[contains(@id, 'signUpName')]")))

input.send_keys("Josh")

如果这仍然抛出异常,我们可以尝试通过 Javascript 设置 input 值:

input = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[contains(@id, 'signUpName')]")))

driver.execute_script("arguments[0].value = 'Josh';", input)

如果这些解决方案都不起作用,我们可能需要查看您正在使用的页面上的一些 HTML,看看这里是否发生了任何其他问题。

【讨论】:

  • IMO,ID 是动态的,您需要调整定位器。
  • 如果没有提供任何 HTML 就很难判断。我想也许//input[contains(@id, 'signUpName')] 也可以在这里工作——我会把它改成这样,因为它更健壮。
【解决方案2】:

ElementNotInteractableException发生在

  • 元素不显示,
  • 元素不在屏幕上,
  • 某些时间元素被隐藏或
  • 在另一个元素的后面

请参考下面的代码来解决这个问题:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait as Wait
    from selenium.webdriver.common.action_chains import ActionChains


    driver = webdriver.Chrome(executable_path=r"C:\New folder\chromedriver.exe")


    driver.set_page_load_timeout("10")
    driver.get("your url")

    actionChains = ActionChains(driver)
    element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, "//input[@id='signUpName16']")))
    actionChains.move_to_element(element).click().perform()

解决方案 2:

element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, "//input[starts-with(@id,signUpName')]"))) # if your signUpName16 element is dynamic then use contains method to locate your element
actionChains.move_to_element(element).click().perform()

【讨论】:

    猜你喜欢
    • 2022-07-01
    • 2020-03-08
    • 2021-12-16
    • 2022-01-07
    • 2019-03-18
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    相关资源
    最近更新 更多