python selenium无法与输入元素交互?

2024-05-12 21:51:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把我的名字放在一个输入框里。这似乎是一个简单的事情,硒是建立做,但我不能找出我做错了什么。你知道吗

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

我知道驱动程序可以工作,因为我可以单击其他元素。我知道xpath是正确的,因为我是从chrome inspector复制的。我得到的错误是

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

我见过有人说要尝试点击或清除元素,所以我也尝试过,但还是失败了。你知道吗

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

这就是name.点击()线

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

Tags: namesendid元素inputbydriverselenium
2条回答

elementNotInteractiableException发生在

  • 元素不显示
  • 元素在屏幕外
  • 某个时间元素被隐藏或
  • 后面是另一个元素

请参考以下代码来解决此问题:

    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()

这里有一些不同的事情可能会出错。如果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,以查看是否有任何其他问题发生在这里。你知道吗

相关问题 更多 >