Typing text into input fields is a common action in web testing to simulate user input.
0
0
Typing text (send_keys) in Selenium Python
Introduction
Filling out a login form with username and password.
Entering search terms in a search box on a website.
Typing data into a form field during automated form submission tests.
Simulating user input to test validation messages.
Automating repetitive data entry tasks in web applications.
Syntax
Selenium Python
element.send_keys('text to type')element is the web element you want to type into, found using locators.
send_keys simulates keyboard typing into that element.
Examples
Types 'Selenium testing' into the search box found by its ID.
Selenium Python
search_box = driver.find_element(By.ID, 'search') search_box.send_keys('Selenium testing')
Types 'user123' into the username input field found by its name attribute.
Selenium Python
username_field = driver.find_element(By.NAME, 'username') username_field.send_keys('user123')
Types 'mypassword' into the password field found by CSS selector.
Selenium Python
password_field = driver.find_element(By.CSS_SELECTOR, 'input[type="password"]') password_field.send_keys('mypassword')
Sample Program
This script opens a login page, types a username and password into input fields, then checks if the text was entered correctly. It prints a success message if all is well.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import time # Setup Chrome driver (adjust path as needed) options = Options() options.add_argument('--headless') # Run in headless mode service = Service() driver = webdriver.Chrome(service=service, options=options) try: driver.get('https://www.example.com/login') # Locate username and password fields username = driver.find_element(By.ID, 'username') password = driver.find_element(By.ID, 'password') # Type text into fields username.send_keys('testuser') password.send_keys('securepass') # Verify typed text (get attribute 'value') assert username.get_attribute('value') == 'testuser', 'Username input failed' assert password.get_attribute('value') == 'securepass', 'Password input failed' print('Test passed: Text typed correctly') finally: driver.quit()
OutputSuccess
Important Notes
Always locate elements using reliable locators like ID or name for stability.
Use get_attribute('value') to verify the text typed into input fields.
Remember to close the browser with driver.quit() to free resources.
Summary
send_keys types text into web elements like input boxes.
Use it to simulate user typing in automated tests.
Verify typed text by checking the element's value attribute.