How to Use Keys in Selenium Python for Keyboard Actions
In Selenium Python, use the
Keys class from selenium.webdriver.common.keys to simulate keyboard keys like Enter, Tab, or Ctrl. Combine send_keys() with Keys constants to perform keyboard actions on web elements.Syntax
Use Keys constants with the send_keys() method on a web element to simulate keyboard input.
element.send_keys(Keys.KEY_NAME): Sends a special key press.Keysis imported fromselenium.webdriver.common.keys.
python
from selenium.webdriver.common.keys import Keys # Example usage: element.send_keys(Keys.ENTER) # Press Enter key
Example
This example opens a browser, navigates to Google, types a search query, and presses Enter using Keys.ENTER.
python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time # Setup WebDriver (Chrome in this example) driver = webdriver.Chrome() try: driver.get('https://www.google.com') time.sleep(2) # Wait for page to load # Find the search box element search_box = driver.find_element(By.NAME, 'q') # Type 'Selenium Python' and press Enter search_box.send_keys('Selenium Python') search_box.send_keys(Keys.ENTER) time.sleep(3) # Wait to see results finally: driver.quit()
Output
The browser opens Google, types 'Selenium Python' in the search box, and submits the search by pressing Enter.
Common Pitfalls
- Not importing
Keysfromselenium.webdriver.common.keyscauses errors. - Using string literals like 'ENTER' instead of
Keys.ENTERwill not work. - Trying to send keys to elements that are not interactable leads to exceptions.
- For key combinations (e.g., Ctrl+C), use
Keys.CONTROLwithsend_keys()properly.
python
from selenium.webdriver.common.keys import Keys # Wrong way (will not work): # element.send_keys('ENTER') # Right way: element.send_keys(Keys.ENTER) # For key combinations: element.send_keys(Keys.CONTROL, 'a') # Ctrl + A to select all
Quick Reference
| Key | Description | Usage Example |
|---|---|---|
| Keys.ENTER | Press Enter key | element.send_keys(Keys.ENTER) |
| Keys.TAB | Press Tab key | element.send_keys(Keys.TAB) |
| Keys.ESCAPE | Press Escape key | element.send_keys(Keys.ESCAPE) |
| Keys.CONTROL | Control key for combinations | element.send_keys(Keys.CONTROL, 'a') |
| Keys.SHIFT | Shift key for combinations | element.send_keys(Keys.SHIFT, 'a') |
| Keys.BACKSPACE | Backspace key | element.send_keys(Keys.BACKSPACE) |
Key Takeaways
Always import Keys from selenium.webdriver.common.keys before using keyboard keys.
Use element.send_keys(Keys.KEY_NAME) to simulate pressing special keys like Enter or Tab.
For key combinations, pass multiple arguments to send_keys, e.g., Keys.CONTROL with a character.
Avoid sending keys to elements that are not interactable to prevent errors.
Use Keys constants instead of string literals for reliable keyboard simulation.