How to Use send_keys in Selenium for Input Automation
In Selenium, use
send_keys to simulate typing text into input fields or other elements that accept keyboard input. First, locate the element using a suitable locator, then call send_keys with the text you want to enter.Syntax
The send_keys method is called on a web element to simulate typing. It takes one or more strings or special keys as arguments.
- element: The web element found by a locator.
- send_keys(value): Sends the string
valueas keyboard input to the element.
python
element.send_keys("text to type")Example
This example opens a browser, navigates to a search engine, finds the search input box, and types a query using send_keys. It then submits the form.
python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys # Setup WebDriver (make sure chromedriver is in PATH) driver = webdriver.Chrome() try: driver.get("https://www.google.com") # Locate the search input box by its name attribute search_box = driver.find_element(By.NAME, "q") # Type the search query search_box.send_keys("Selenium send_keys example") # Press Enter to submit search_box.send_keys(Keys.RETURN) # Wait for results to load driver.implicitly_wait(5) finally: # Close the browser driver.quit()
Output
Browser opens Google, types 'Selenium send_keys example' in search box, and submits search.
Common Pitfalls
Common mistakes when using send_keys include:
- Trying to send keys to an element that is not interactable or not visible, causing errors.
- Using incorrect locators that fail to find the element.
- Not clearing existing text before typing, which may append text instead of replacing.
- Forgetting to import special keys like
Keyswhen sending keys like Enter or Tab.
Always ensure the element is ready for input before calling send_keys.
python
from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys # Wrong: sending keys to a non-input element button = driver.find_element(By.ID, "submit") button.send_keys("text") # This will raise an error # Right: send keys to input element input_box = driver.find_element(By.ID, "username") input_box.clear() # Clear existing text input_box.send_keys("myusername")
Quick Reference
Tips for using send_keys effectively:
- Use reliable locators like
By.IDorBy.NAME. - Clear input fields with
clear()before typing if needed. - Use
Keysfor special keyboard keys (Enter, Tab, etc.). - Wait for elements to be visible and enabled before sending keys.
Key Takeaways
Use send_keys on a located web element to simulate typing text or special keys.
Always ensure the element is interactable before sending keys to avoid errors.
Clear input fields first if you want to replace existing text.
Use Selenium's Keys class to send special keys like Enter or Tab.
Choose stable locators to reliably find input elements.