Key combinations (key_down, key_up) in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Setup WebDriver (assumes chromedriver is in PATH) driver = webdriver.Chrome() try: driver.get('https://example.com') # Replace with actual URL containing the input field wait = WebDriverWait(driver, 10) input_field = wait.until(EC.element_to_be_clickable((By.ID, 'input-text'))) # Click to focus the input field input_field.click() # Verify input field is focused assert driver.switch_to.active_element == input_field, "Input field is not focused" # Use ActionChains to press Ctrl + A actions = ActionChains(driver) actions.key_down('\ue009').send_keys('a').key_up('\ue009').perform() # \ue009 is CONTROL key # Verify all text is selected # Get selection start and end from the input field using JavaScript selection_start = driver.execute_script('return arguments[0].selectionStart;', input_field) selection_end = driver.execute_script('return arguments[0].selectionEnd;', input_field) input_length = len(input_field.get_attribute('value')) assert selection_start == 0 and selection_end == input_length, "Not all text is selected" finally: driver.quit()
This script opens the webpage and waits until the input field with id 'input-text' is clickable. It clicks the input field to focus it and asserts that the field is focused by comparing the active element.
Then, it uses Selenium's ActionChains to simulate pressing the Control key down, pressing 'a', and releasing Control key, which triggers the 'select all' shortcut.
To verify the selection, it runs JavaScript to get the selection start and end positions inside the input field. If the selection covers the entire text length, the test passes.
Explicit waits ensure the element is ready before interaction, and assertions confirm each step's success.
Now add data-driven testing with 3 different input texts to verify Ctrl + A selects all text correctly.