Selenium sendKeys(): A Complete Guide

Solomon Eseme

Posted On: May 21, 2024

view count497113 Views

Read time17 Min Read

While performing automation testing with Selenium, developers and testers need to automate different scenarios, like typing text into form fields, entering passwords in boxes, and more. This is where the Selenium sendKeys() method helps achieve this.

In this blog, we’ll delve into how to pass values to text fields, text areas, and input fields using the Selenium sendKeys() method.

What is Selenium sendKeys()?

When running automated tests using Selenium, the sendKeys() method simulates keyboard input on a specific WebElement. This method is part of the WebElement interface and allows you to interact with input fields, text areas, and other elements that accept user input on a web page.

The sendKeys() method sends a series of keystrokes to the selected WebElement, effectively inputting the specified text or key combinations. It is handy for automating form filling, triggering events, or interacting with elements that require user input.

In our case above, we used the Selenium sendKeys() method to simulate the keyboard input on our email and password fields.

Here’s an example of how to use the Selenium sendKeys() in software projects:

It looks quite simple. Well, it is not complicated, but this simple line of code allows you to input data into any text field in your project, including textarea, input and password fields, etc.

However, the Selenium sendKeys() method is not the only method. There are alternative methods besides sendKeys() to input data into text fields during automated testing.

In the next section of this blog on using Selenium sendKeys(), let’s explore some of the areas for using the sendKeys() method.

Importance of sendKeys() in Selenium Automation

The sendKeys() method is important in Selenium testing because it allows you to programmatically simulate keyboard input and interact with WebElements on a web page.

It is beneficial in automated form filling, user login, triggering events, and validating the behavior of various input elements on a website.

Here are some areas of application where the sendKeys() method can be used:

Form Filling

It is one of the most crucial use cases of the sendKeys() method. Websites can have forms where users need to fill in information. Automated testing often requires completing forms with various input values to ensure the website functions correctly. The Selenium sendKeys() allows testers to automate this process efficiently.

Here’s an example to demonstrate form filling with Selenium sendKeys():

User Authentication

Suppose you are building an application that requires complete authentication and authorization. In that case, you need a way to implement automated testing that requires you to input the correct details of the authenticated user.

With the sendKeys() method, you can simulate entering an email and password into login fields, allowing you to verify if the login process works as expected.

Here’s an example to demonstrate authentication with Selenium sendKeys():

Triggering Events

Some websites use user interactions (e.g., typing or key presses) to trigger specific events or actions. The sendKeys() method enables you to simulate these user interactions and ensure the correct behavior of event-driven functionalities.

A good example could be validating user input while the user is typing the information in the form. The sendKeys() function allows us to activate, listen to, or trigger HTML form events when users interact with our forms.

In the example below, we are sending the Web automation to the search input field and using sendKeys to activate the search by pressing the ENTER key.

Dropdown Selection

While handling dropdowns in Selenium to select options from a list, the sendKeys() method lets you send arrow keys and enter to help you simulate choosing an option from the dropdown menu.

In the example below, we use a combination of arrow keys and ENTER to simulate the selection of items from a dropdown list. In this case, we selected the third option because we sent the ARROW_DOWN key twice and used the ENTER key for selection.

File Upload

When testing file upload functionality, the Selenium sendKeys() method can be used to input the file path into the file input field.

File uploads are crucial to some web applications, especially when filling out personal details and uploading your image.

In the example below, we uploaded a text file to the server using Selenium sendKeys():

There are unlimited use cases of the Selenium sendKeys() method. We have only touched a few. However, the benefits apply irrespective of the programming language that supports it.

In the next section, we will demonstrate how to use the Selenium sendKeys() method using Java and JavaScript.

How to Use Selenium sendKeys() in Java?

In this section, you will learn how to use Selenium sendKeys() in Java to interact with WebElements.

Test Scenario:

  1. Open the LambdaTest website.
  2. Locate the WebElement to enter the email address.
  3. Enter your email address.
  4. Click on the SIGN UP button.

Let us now see what the code for the above use case would look like, and then we will understand the code line-by-line.

Code Walkthrough:

  • @BeforeClass annotation: The method setUp() contains the generic code to instantiate the ChromeDriver and navigate to the LambdaTest website. The page is then maximized.
  • @AfterClass annotation: Similar to the setUp() method, the burnDown() method closes the browser instance.
  • @Test annotation: This is the method consisting of our test case. We simply locate the text field where we have to enter the email ID and then pass on the string (our email ID) to the sendKeys() method. Next, we locate the SIGN UP button and click it.

Note: The code to use the Selenium sendKeys() method can also be written as shown below:

On running the above test, you will see that the browser actions are performed, and your email is entered into the email ID text field.

Entering Text Without Selenium sendKeys()

Although Selenium sendKeys() works almost every time, there might be a case where the text input box is disabled, and you need to pass some text to the field. In such scenarios, you need to use a sendKeys() alternative to enter text in Selenium.

Before we move on to the use case, remember that this is not the recommended way to test as the UI blocks you from entering any text in a field. Just for the sake of understanding our use case, let us consider such a scenario.

Now, you might wonder, if not the Selenium sendKeys() method, then what? One of the most effective ways to send input to text fields is to use the JavaScriptExecutor.

Let’s see what the code would look like:

As seen from the above code, we are merely passing the text box’s arguments as a script for the JavaScriptExecutor and not using the Selenium sendKeys() method.

Try using these code lines in our example above by replacing the sendKeys() code and seeing that you will get the same results as with the sendKeys() method.

Erasing Text Using Selenium sendKeys()

Next, let us consider a scenario where we need to verify that we can clear or delete the string entered in the text field. To achieve this case, we will use the Selenium clear() method, which simply erases whatever text is entered in the text field.

Consider the below test script for the same:

The code is the same as we explained earlier, but the only addition is the clear() method used for the email WebElement. This clear() method would erase the text entered in the text field, and you can further enter the text using the sendKeys() method as per your requirement.

Now that you understand how to use the Selenium sendKeys() method, let’s see how the LambdaTest Selenium Grid cloud can efficiently execute your tests across different system configurations.

LambdaTest is an AI-powered test orchestration and execution platform that enables devs and testers to perform test automation using Selenium Java and Selenium JavaScript at scale on a remote test lab of 3000+ real desktop browsers and operating systems.

Subscribe to the LambdaTest YouTube Channel for quick updates on the tutorials around automation testing, WebdriverIO, and more.

Implementing Selenium sendKeys() on Cloud Grid

LambdaTest provides an easy solution for executing your tests across multiple combinations by leveraging capabilities. These capabilities can be generated directly from the LambdaTest Automation Capabilities Generator and integrated into your Selenium tests.

Note that we will use the example above for execution on the LambdaTest cloud for one browser. Still, as explained in our blog on parallel testing, you can use the same test to perform cross browser testing by changing the capabilities and using @DataProvider.

You can find these results under the LambdaTest Web Automation Dashboard.

How to Use Selenium sendKeys() in JavaScript?

In this section, you will learn how to use Selenium sendKeys() in JavaScript to interact with WebElements in Google Chrome.

Here are the steps for using the sendKeys() method in Selenium JavaScript:

Step 1: Create a New Project

  1. Open a terminal or command prompt.
  2. Create a new folder for your project using the below command:
  3. mkdir sendkeys-selenium-tutorial

  4. Navigate into the project folder using the below command:
  5. cd sendkeys-selenium-tutorial

  6. Initialize a new Node.js project by running the below command:
  7. npm init -y

Step 2: Set Up VS Code

  1. Open VS Code.
  2. Navigate to your project folder by selecting File > Open Folder.
  3. Create a new file named test.js inside your project folder.
  4. Step 3: Import Required Dependencies

    Import the required modules for Selenium WebDriver in the test.js file.

    Step 4: Set Up Chrome WebDriver

    Create a function to set up the Chrome WebDriver instance:

    Step 5: Set Up the WebDriver Instance

    Call the setupDriver() function to create a WebDriver instance (driver) and set up the Chrome WebDriver. This allows us to interact with the Chrome browser programmatically. Lastly, note that you can use other browsers with their respective drivers.

    Step 6: Navigate to Google Homepage

    Use the driver.get(‘https://www.google.com’) to navigate to Google’s homepage.

    Step 7: Find the Search Input Element and Send the Search Query

    Locate the search input element on the page using driver.findElement(By.name(‘q’)). Then, use the sendKeys() method to send the text Selenium JavaScript to the search input to simulate typing.

    Step 8: Submit the Search Using the Enter Key

    Use sendKeys(Key.ENTER) to send the Enter key after entering the search query. This submits the search and triggers the search results.

    Below is a table showing some key combinations most commonly used with the sendKeys() method:

    Key Description
    ENTER Simulate the ENTER key on your keyboard.
    ADD Simulate the ADD key on your keyboard.
    BACK_SPACE Simulate the BACKSPACE key on your keyboard.
    ALT Simulate the ALT key on your keyboard.
    ARROW_DOWN Simulate the ARROW DOWN key on your keyboard.
    ARROW_UP Simulate the ARROW UP key on your keyboard.
    CANCEL Simulate the CANCEL key on your keyboard.
    COMMAND Simulate the COMMAND key on your Mac keyboard.
    CONTROL Simulate the CTRL key on your keyboard.
    DELETE Simulate the DELETE key on your keyboard.

    This table may give you an insight into where we get the ENTER key combination used in the test script:

    Step 9: Wait for the Search Results Page to Load

    Use the driver.wait() method to wait until the page title contains the text Selenium JavaScript. This ensures that the search results page has loaded before proceeding. In cases where the title changes or does not load. The test script will throw the Selenium exception and notify you of the error.

    Step 10: Print the Page Title

    Get the title using the driver.getTitle() method and store it in the variable pageTitle. Then, you print the title to the console using the console.log() function.

    Step 11: Handle Any Errors That Occur During the Execution

    If errors occur during the execution of the try block (e.g., an element not found or page navigation issues), they will be caught in the catch block. The error message is logged to the console using the console.error() function.

    Step 12: Quit the Driver After the Test Is Finished

    Use the driver.quit() in the finally block to close the browser and clean up the WebDriver resources after the test is finished. This ensures the browser is closed properly, even if an error occurs during the test.

    Step 13: Call the Function to Run the Test

    Call the performSearch() function to start the test and execute the steps defined in the function.

    Step 14: Test Execution

    1. Open a terminal in VS Code by heading to View > Terminal.
    2. Run the test using Node.js by running the below command:

      node test.js

    It’s important to note that there are some cases where the input field of the website you’re trying to fill might be disabled when you try to input data into it. In that case, the sendKeys() method may not work. Therefore, you need an alternative if the sendKeys() function is not working.

    Let’s understand this use case where we enter text in a textbox without using the sendkeys() method.

    Github

    Entering Text Without Selenium sendKeys()

    JavaScriptExecutor can be a perfect alternative to input data into a field without using the sendKeys() method. However, it is generally not recommended, as the UI blocks you from entering any text in a field.

    Let’s take an example using Selenium JavaScriptExecutor to input an email address into a disabled email field.

    Entering Text Without Selenium sendKeys()

    Below is a code snippet showing how to do it:

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

    Let’s go through some examples of using sendKeys() to understand how this powerful method can be used for web automation.

    Each example will demonstrate a specific use case, showcasing how to interact with different WebElements using sendKeys(). We will run our tests on a cloud-based grid like LambdaTest.

    To get started, generate capabilities based on the configuration of your automated testing suites using the LambdaTest Automation Capability Generator and integrate them into your Selenium tests.

    Here’s the test script that runs our tests on a cloud grid:

    Once you run the tests, head over to the LambdaTest Web Automation Dashboard to view your test results.

    Use Case I: Entering Text

    This example demonstrates locating a text field on a web page and using the sendKeys() method to enter text.

    In this case, the text lambdatest@test.com is entered into the text field with the ID input-email The submit() method is optionally used to submit the form after the text entry.

    Use Case II: Entering Special Characters

    In this example, the code locates a search box on the web page and uses the sendKeys() method to enter the text LambdaTest. After that, the Key.ENTER from the selenium-webdriver package is used to simulate pressing the Enter key, triggering a search action.

    Here is the code snippet that imports the selenium-webdriver package.

    It contains a Key – an object containing all the key codes, including ENTER, BACK_SPACE, etc.

    Use Case III: Clearing Text

    This example demonstrates using the sendKeys() method to enter text LambdaTest into a text field. After entering the text, the clear() method is used to clear the contents of the text field. The two-second sleep between actions is optional and added to observe the results.

    Conclusion

    In this blog on Selenium sendKeys(), we discussed using the sendKeys() method in Java and JavaScript to handle different test scenarios, like entering the text in the field. We also looked at some advanced use cases of the sendKeys() method and leveraging the LambdaTest platform to run Selenium tests.

    Moreover, to enhance your skills and validate your knowledge of Selenium with Java and JavaScript, you can consider taking the LambdaTest Selenium Java 101 and Selenium JavaScript 101 certifications, which gives you hands-on experience with real-life use cases of Selenium automation using Java and JavaScript.

    In a nutshell, the sendKeys() method in Selenium can be helpful for developers and testers when automating data entry in automated tests. It allows you to simulate input without manually entering data in a form, reducing the time and effort spent on repetitive tasks.

    Frequently Asked Questions (FAQs)

    How to use sendKeys in Selenium?

    sendKeys() is a method within Selenium that is used to simulate typing text into a WebElement on a web page. It can automate data entry in web testing or scraping scenarios.

    How to pass the Enter key in Selenium?

    To pass the Enter key in Selenium:

    1. Locate the element you want to interact with using Selenium.
    2. Send the Enter key using the Keys.ENTER method.
    3. element.send_keys(Keys.ENTER)to simulate pressing Enter.

    What is the difference between sendKeys and type in Selenium?

    sendKeys() method simulates keyboard input into a web element, allowing you to send text or key combinations like Enter or Ctrl. However, the type() method isn’t a standard Selenium method.

Author Profile Author Profile Author Profile

Author’s Profile

Solomon Eseme

Solomon is a Software Engineer and Content Creator who is geared toward building high-performing and innovative products following best practices and industry standards. He blogs regularly at Masteringbackend.com

Blogs: 4



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free