python selenium can't clear input field

爱⌒轻易说出口 提交于 2020-06-17 09:47:45

问题


I try to select my input with selenium but when I use this it doesn't work:

driver = self.driver
password = driver.find_element_by_xpath("//input[@name='password']")
password.clear()
password.send_keys(password)
password.send_keys(Keys.RETURN)

# the sentence below doesn't work
password.send_keys(Keys.COMMAND, 'a')
password.send_keys(Keys.DELETE)

I am using Mac so Keys.CONTROL doesn't work, can anyone help me how to select the input or how to clear it?

Thanks


回答1:


Mac cannot use COMMAND you need Keys.BACKSPACE Try:

driver = self.driver
password = driver.find_element_by_xpath("//input[@name='password']")
password.clear()
password.send_keys(password)
password.send_keys(Keys.RETURN)
#password = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='password']")))
#or
#time.sleep(1)
for i in range(len(password)):
    password.send_keys(Keys.BACKSPACE)



回答2:


You have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    password = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='password']")))
    password.click()        
    password.clear()
    password.send_keys("Tijmen")
    
  • Using XPATH:

    password = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='password']")))
    password.click()
    password.clear()
    password.send_keys("Tijmen")
    
  • Note : You have to add the following imports :

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

Reference

You can find a couple of relevant discussions in:

  • How to clear text field before sending keys selenium c#
  • clear() does not clear the textbox with selenium and python and firefox
  • InvalidElementStateException when attempting to clear text through Selenium


来源:https://stackoverflow.com/questions/59635447/python-selenium-cant-clear-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!