如何find_element(By.XPATH)并在selenium中发送密钥?

问题描述 投票:0回答:3

尝试更新我的代码以使用

"driver.find_element(By.XPATH..."
而不是
"driver.find_elements_by_xpath(..."
,但在发送密钥时我不断收到以下错误:

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

这是我的代码:

driver = webdriver.Chrome(PATH)
link_login = "https://www.wyzant.com/tutor/jobs"

driver.get(link_login)

username_input = driver.find_element(By.XPATH, "//*[@id='Username']")[1]
username_input.send_keys("Test")
python selenium google-chrome xpath webdriver
3个回答
7
投票

使用

find_elements
而不是
find_element
来选择元素,就像在示例中一样:

driver.get('https://www.wyzant.com/tutor/jobs')
username_input = driver.find_elements(By.XPATH, "//*[@id='Username']")[1]
username_input.send_keys("Test")

或更改您的 xpath 以选择更具体的

'//form[@class="sso-login-form"]//*[@id="Username"]'
:

driver.get('https://www.wyzant.com/tutor/jobs')
username_input = driver.find_element(By.XPATH, '//form[@class="sso-login-form"]//*[@id="Username"]')
username_input.send_keys("Test")

4
投票
  1. 尝试使用更精确的 XPath 定位器。
  2. 整个 XPath 表达式应位于
    (By.XPATH, "your_xpath_expression")
  3. 您还应该使用预期条件显式等待

这应该有效:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//form[@action='/sso/login']//input[@id='Username']"))).send_keys(your_user_name)

您将需要导入这些导入:

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

1
投票

要在 Username 字段中发送 字符序列,您需要为 element_to_be_clickable() 引入 WebDriverWait,并且您可以使用以下任一定位器策略

  • 使用CSS_SELECTOR

    driver.get("https://www.wyzant.com/tutor/jobs")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "form.sso-login-form input#Username"))).send_keys("rushi")
    
  • 使用XPATH

    driver.get("https://www.wyzant.com/tutor/jobs")   
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//form[@class='sso-login-form']//input[@id='Username']"))).send_keys("rushi")
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
© www.soinside.com 2019 - 2024. All rights reserved.