Selenium automates browser interactions, and typing into a form field is one of the most common actions.
Whether you are logging in, searching, or filling out a form, this guide shows how to locate and enter text into input fields using clean and practical code examples.
Pre-requisites
Before you start, install the following:
- Java Development Kit (JDK) or a supported language binding (Java, Python, C#, etc.)
- Selenium WebDriver installed
- A test browser such as Chrome or Firefox
- Selenium-compatible IDE (e.g. Eclipse, IntelliJ, VS Code)
- Required browser drivers (e.g. chromedriver for Chrome)
Install the Selenium package via pip (Python):
pip install selenium
For Java, include the Selenium dependency using Maven or manually add the JARs.
Locate the Text Box Element
To type in a textbox, you first need to locate it. Selenium provides multiple strategies:
- By.id(“element_id”)
- By.name(“element_name”)
- By.xpath(“//input[@type=’text’]”)
- By.cssSelector(“input.classname”)
Example (Python):
from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get("https://example.com") textbox = driver.find_element(By.ID, "username")
Type into the Text Box using sendKeys()
Once you’ve located the textbox, use sendKeys() to enter text.
For Python:
textbox.send_keys("your_username")
For Java:
WebElement textbox = driver.findElement(By.id("username")); textbox.sendKeys("your_username");
You can also clear an existing value before typing:
textbox.clear() textbox.send_keys("new_input")
This method simulates keyboard input, just like a real user.
Conclusion
Entering text into a textbox in Selenium is easy. First, find the element. Next, use sendKeys() to enter text. This works in form fields, search boxes, and logon forms. With practice in this, you can write stable test scripts for UI automation.
Once you’ve mastered typing into text fields and interacting with elements using Selenium, the next challenge is ensuring your tests work across different browsers and devices. Instead of maintaining multiple local setups, you can use BrowserStack Automate to run your Selenium scripts on real browsers and devices in the cloud, no installation or configuration required