简体   繁体   中英

How can I define send_keys for python function?

I need advice on how to call send_keys for user input. If I assign a variable for the line self.browser.find_elements_by_id ("Login1_UserName") and then send it to send_keys, the solution does not work. What am I doing wrong?

 def login(Self):
     # login to the app
     username = self.browser.find_elements_by_id ("Login1_UserName")
     username.send_keys ("userone")

find_elements_* would return a List and you can't invoke send_keys() on a List . So you need to replace find_elements_* with find_element_* and you can use the following Locator Strategies :

def login(Self):
    # login to the app
    self.browser.find_element_by_id("Login1_UserName").send_keys("userone")

As per best practices, while invoking send_keys() you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following solutions:

  • Using ID :

     WebDriverWait(self.browser, 20).until(EC.element_to_be_clickable((By.ID, "Login1_UserName"))).send_keys("Tomasito")
  • Using CSS_SELECTOR :

     WebDriverWait(self.browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#Login1_UserName"))).send_keys("Tomasito")
  • Using XPATH :

     WebDriverWait(self.browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='Login1_UserName']"))).send_keys("Tomasito")
  • 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

This is because you have used find_elements_by_id("Login1_UserName") it will return list NOT the element.You should use find_element_by_id("Login1_UserName")

def login(Self):
     # login to the app
     username = self.browser.find_element_by_id("Login1_UserName")
     username.send_keys("userone")

Try this code see if this work.

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

driver=webdriver.Chrome("path of chrome driver")
driver.get('url')
username=WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.ID,'Login1_UserName')))
username.send_keys("userone")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM