0
0
Selenium-pythonHow-ToBeginner ยท 3 min read

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.
  • Keys is imported from selenium.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 Keys from selenium.webdriver.common.keys causes errors.
  • Using string literals like 'ENTER' instead of Keys.ENTER will not work.
  • Trying to send keys to elements that are not interactable leads to exceptions.
  • For key combinations (e.g., Ctrl+C), use Keys.CONTROL with send_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

KeyDescriptionUsage Example
Keys.ENTERPress Enter keyelement.send_keys(Keys.ENTER)
Keys.TABPress Tab keyelement.send_keys(Keys.TAB)
Keys.ESCAPEPress Escape keyelement.send_keys(Keys.ESCAPE)
Keys.CONTROLControl key for combinationselement.send_keys(Keys.CONTROL, 'a')
Keys.SHIFTShift key for combinationselement.send_keys(Keys.SHIFT, 'a')
Keys.BACKSPACEBackspace keyelement.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.