Selenium sendKeys(): How to Use It for Input Automation [Guide + Examples]

Selenium sendKeys() method

Selenium is a versatile tool for automating web applications, as it can handle nearly every type of interaction on a website. Entering text into input or text fields is one of the fundamental actions a user performs especially to validate form pages. For instance, if a user needs to test a form with 20 fields, manually entering data and submitting the form could take around two minutes. However, with a Selenium script, a tester can automate this task and complete it in just a few seconds via Selenium’s sendKeys() method.

What is sendKeys in Selenium?

In Selenium, sendKeys() is a method which is used to simulate keyboard input on a specific WebElement. It is a WebElement interface’s method which is used to enter data as input to a text field, text area and other form elements. This helps in automating the process of entering data into text fields which makes the process faster and reliable to perform multiple tasks.

For example:

WebElement emailField = driver.findElement(By.id("email"));
emailField.sendKeys("john@abc.com");

The sendKeys() method accepts a string as an argument and types that into the desired element. In the above example, the email field is located and “john@abc.com” is entered into the email field.

How does the sendKeys method work?

Selenium’s sendKeys() method is used to mimic keyboard input in a web application. When a user needs to enter text into a text field, they typically identify the field, type the text, and then see the input appear in that field. Similarly, Selenium performs this process programmatically through the following series of actions.

1.      Locate the element and focus: The first step is to locate the element where you need to input data. Selenium provides different locator strategies to identify the web elements such as by class name, ID, name, XPath and more and later it sets focus on the element.

2.      sendKeys method: After the element is located and focussed, sendKeys() method is used to enter the data into the desired text or input field. This method takes in a string as an argument which represents the data to be entered and is entered in the field one by one simulating real keyboard input.

3.      Trigger the events: Once the sendKeys() method is called and as the keys are typed, a series of JavaScript events is triggered which includes generating keyboard events such as keydown, keyup and keypress.

Where is sendKeys() method used in Selenium?

sendKeys() method is primarily used to simulate keyboard interactions. Below are some scenarios where the sendKeys() method can be used to test various interactions that a user would normally perform with a keyboard.

1.      Input validation: To test a login page, a user needs to validate that the entered email id and password are valid. This includes that the email is in correct format and the password adheres to the required password policy. The sendKeys() method can be used in this context to enter the necessary text into the appropriate fields and ensure that the inputs are rightly populated.

2.      Search results evaluation: Most web applications include a basic feature which is search functionality. To test it effectively, you need to input a variety of data to ensure the feature behaves as expected. This is made possible with the sendKeys() method, which allows you to perform regression testing on the search functionality against a wide range of inputs. By entering different search keywords, you can verify that the application returns the expected results.

3.      Simulating shortcut keys: Some web applications have special functions enabled where users often use keyboard shortcuts for actions such as selecting all text (Ctrl+A), copying (Ctrl+C), Pasting (Ctrl+V), etc. With the sendKeys() method you can easily simulate shortcut keys or key combinations.

For example:

WebElement search = driver.findElement(By.cssSelector("textarea[name='q']"));
search.sendKeys("Selenium");
search.sendKeys(Keys.chord(Keys.CONTROL, "a"));

In the above code snippet, search element is located and “Selenium” text is entered in it. With “Keys.chord(Keys.CONTROL, “a”)” the desired text is selected.

How to use sendKeys in Java?

To learn how to use sendKeys in Java, consider TestGridIO’s sign up form.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class SendKeysInJava {
          	
          	public static void main(String args[]) {
                         	WebDriver driver=new ChromeDriver();
                         	driver.get("https://public.testgrid.io/signup");
                         	WebElement fullName= driver.findElement(By.cssSelector("input#full_name"));
                         	WebElement businessEmail=driver.findElement(By.cssSelector("input#business_email"));
                         	fullName.sendKeys("Sonal Dwivedi");
                         	businessEmail.sendKeys("abc@xyz.com");
                         	driver.quit();
          	}
}

Please note, automating login forms especially for websites you do not own or have permissions to test is discouraged. This example is for demonstration purposes only.

In the above program, full name and business email fields are first located and then sendKeys() method is used to enter the required text in the input boxes.

How to type in a text field without using send keys method

sendKeys() method is the standard and most reliable way of entering text using Selenium, and it works in most cases. However, there may be instances where the input field is disabled or hidden. In such cases, you need to rely on alternative methods such as using JavaScript or the Actions class.

Please note if a text field is hidden or disabled, it is generally not recommended to automate it, as it is intentionally restricted from user input. The below example is provided for demonstration purposes only.

If sendKeys() method cannot be used directly in the fullName and businessEmail fields as mentioned in above program, the following two approaches may help:

Using JavaScriptExecutor method:  

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class UsingJavaScriptExecutor {
          	
          	public static void main(String args[]) {
                         	WebDriver driver=new ChromeDriver();
                         	driver.get("https://public.testgrid.io/signup");
                         	WebElement fullName= driver.findElement(By.cssSelector("input#full_name"));
                         	WebElement businessEmail=driver.findElement(By.cssSelector("input#business_email"));
                         	JavascriptExecutor js = (JavascriptExecutor)driver;
                         	js.executeScript("arguments[0].value='Sonal Dwivedi';", fullName);
          	          	js.executeScript("arguments[0].value='abc@xyz.com';", businessEmail);
                         	driver.quit();
          	}
}

In the above code snippet, the arguments of a text box are used as a script for the JavaScriptExecutor instead of using the sendKeys() method.

Using Actions class:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
 
public class UsingActionsClass {
          	
          	public static void main(String args[]) {
                         	WebDriver driver=new ChromeDriver();
                         	driver.get("https://public.testgrid.io/signup");
                         	WebElement fullName= driver.findElement(By.cssSelector("input#full_name"));
                         	WebElement businessEmail=driver.findElement(By.cssSelector("input#business_email"));
                         	fullName.click();
                         	Actions action = new Actions(driver);
                         	action.sendKeys("Sonal Dwivedi").perform();
                         	businessEmail.click();
                         	action.sendKeys("abc@xyz.com").perform();
                         	driver.quit();	
          	}
}

In the above code snippet, click() method of WebElement interface is used to focus the desired element and then sendKeys() method of Actions class is used to enter text.

Challenges and limitations in using sendKeys()

1.      Interfering with other elements or applications: Using the sendKeys() method in Selenium automation may sometimes disrupt the normal execution by sending input to the wrong element or even to another application if it is in focus and capable of receiving system-level keyboard input.

2.      Works with limited input types: The sendKeys() method works only with a limited set of form elements, such as <input> and <textarea> tags, that are visible, enabled, and not hidden or covered by other elements. It cannot be used to simulate keyboard input for tags like <span>, <div>, drop downs (<select>), radio buttons or checkboxes.

3.      Timing issues: Selenium tests that use sendKeys() can be prone to timing-related issues, as they depend on the application responding consistently and within expected timeframes. If the application is slow to load, the sendKeys() method may attempt input before the element is ready, causing test failures.

4.      Inconsistent behaviour across different browsers: Different browsers use different engines to render web pages for example- Chrome uses Blink while Firefox uses Gecko. These rendering engines can differ in how they handle focus, special characters, and keyboard events. As a result, the behaviour of the sendKeys() method may vary slightly across browsers.

5.      Hidden or disabled elements: The sendKeys() method in Selenium does not work on elements that are hidden (visibility: hidden, display: none) or disabled (disabled attribute). If it is used for such elements, Selenium will throw exceptions such as ElementNotInteractableException or InvalidElementStateException.

Conclusion

The sendKeys() method plays an important role in automating test cases related to form validations. It allows testers to easily simulate user input by entering text into various input fields. The method is straightforward to use, with a simple and readable syntax, making it convenient for automating data entry in forms.