0
0
Selenium Javatesting~5 mins

Typing text (sendKeys) in Selenium Java

Choose your learning style9 modes available
Introduction

Typing text into input fields is how you simulate a user entering information on a webpage. It helps test if forms and search boxes work correctly.

Filling out a login form with username and password.
Entering search terms in a search box on a website.
Typing data into a registration or contact form.
Testing if input fields accept and display typed text correctly.
Syntax
Selenium Java
WebElement element = driver.findElement(By.id("elementId"));
element.sendKeys("text to type");

Use sendKeys() on a WebElement to type text into input fields.

Make sure to locate the element correctly before typing.

Examples
Types 'myUser123' into the input field with the name 'username'.
Selenium Java
driver.findElement(By.name("username")).sendKeys("myUser123");
Finds the search box by CSS class and types 'Selenium testing' into it.
Selenium Java
WebElement searchBox = driver.findElement(By.cssSelector("input.search"));
searchBox.sendKeys("Selenium testing");
Types an email address into the input field identified by its placeholder attribute.
Selenium Java
driver.findElement(By.xpath("//input[@placeholder='Email']")).sendKeys("test@example.com");
Sample Program

This test opens a login page, types 'testUser' into the username field and 'pass123' into the password field, then prints a success message.

Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class TypingTextTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/login");
            WebElement usernameField = driver.findElement(By.id("username"));
            usernameField.sendKeys("testUser");
            WebElement passwordField = driver.findElement(By.id("password"));
            passwordField.sendKeys("pass123");
            System.out.println("Text typed successfully.");
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Always wait for the element to be visible before typing to avoid errors.

Use clear() method if you want to erase existing text before typing new text.

Summary

sendKeys() types text into input fields in Selenium.

Locate the element first, then call sendKeys() with the text.

This simulates user typing and helps test form inputs.