Selenium SendKeys : All You Need To Know

Selenium SendKeys : All You Need To Know

Selenium automation is not just about navigating and clicking through the links. Yes, you can use it to switch tabs, find broken links, or even drag and drop directly. But there is a lot more to it. An essential aspect of test automation is passing values to the text fields. In this article, we’ll delve into how Selenium helps us pass values to text fields using the Selenium sendKeys() method. Let us start on our journey to learn how to sendkeys in Selenium.

What Is Selenium sendKeys() Method?

Selenium provides sendKeys() method to input content in editable text fields or password fields in a webpage. These fields are like the typical web elements present on the web page that can be identified using any of the Selenium locators. You can refer to our article on Selenium locators to learn more about the different locators you can use.

Let us understand the utility of the sendKeys() method through an example. Consider the below use-case:

  • Open the website > LambdaTest
  • Locate the web-element to enter the email address.
  • Enter your email address.
  • Click on the ‘Start Free Testing’ 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.

package sendkeys;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class SendkeysTest {

WebDriver driver;

       //Method to set up the browser and open the dummy website
       @BeforeClass
       public void setUp() {

              System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\drivers\\chromedriver.exe");
              driver = new ChromeDriver();
              driver.get("https://www.lambdatest.com");
              driver.manage().window().maximize();
       }

       @Test
       public void testSendkeys() {
              //Locate the email and use sendkeys to pass the email to the field
              driver.findElement(By.id("useremail")).sendKeys("----your email id----");

              //Locate the Start Free Testing button and click it
              driver.findElement(By.xpath("//*[@id='testing_form']//button")).click();
       }


       @AfterClass
       public void burnDown() {
              driver.quit();
       }

}

Let us first understand the code above and then see the execution part.

  • The code under @BeforeClass method- The method setUp() contains the generic code to instantiate the ChromeDriver and navigate to the LambdaTest] website. The page is then maximized.
  • The code under @AfterClass method- Similar to the setUp method, the burnDown() method simply closes the browser instance.
  • The code under the main @Test method- 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 (which is our email ID) to the sendKeys() method. Next, we locate the ‘ Start Free Testing ’ button and click the same.

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

WebElement emailField = driver.findElement(by.id(“useremail”));
emailField.sendKeys(“---your email id---”);

This is just the bifurcation of the web element and then passing the string value to the text box.

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.
Did you see how easy the Selenium sendKeys() method is?

Using Selenium sendKeys To Erase Text

Next, let us consider a scenario where we need to verify that we are able to 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 code for the same-

package sendkeys;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class SendkeysTest {

WebDriver driver;

       //Method to set up the browser and open the dummy website
       @BeforeClass
       public void setUp() {

              System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\drivers\\chromedriver.exe");
              driver = new ChromeDriver();
              driver.get("https://www.lambdatest.com");
              driver.manage().window().maximize();
       }

       @Test
       public void testSendkeys() {
              //Locate the email and use sendkeys to pass the email to the field
              WebElement email = driver.findElement(By.id("useremail"));
              email.sendKeys("---your email id---");

              // Erase the text entered in the email id field
              email.clear();
       }


       @AfterClass
       public void burnDown() {
              driver.quit();
       }

}

The code is the same as we explained earlier, but the only addition is the clear() method used for the email web element. 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 we have seen how to sendKeys() in Selenium with its implementation, we hope you understand it better. We have also seen how we can erase the string or text already entered in the text field using the clear() method. We will now explore some other options to enter text in the text field without using sendKeys().

How Can We Type In Selenium Without Using sendKeys?

Although 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, sendKeys() would not work, and you might have to try some alternate approach. Before we move onto 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 be wondering if not Selenium sendKeys, then what? One of the most effective ways to send input to text fields is to use the JavaScriptExecutor, which we will discuss below.

Using The JavaScriptExecutor

We will now use JavaScriptExecutor to locate the text box and then pass the text value to it. Let us see how the code for it would look like-

JavascriptExecutor jse = ((JavascriptExecutor)driver);            
WebElement email = driver.findElement(By.id("useremail"));
jse.executeScript("arguments[0].value='---your email id---';", email);

As can be seen from the above code, we are merely passing the text box’s arguments as a script for the JavaScriptExecutor and not using sendKeys(). 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.

Now that you understand how to sendKeys() in Selenium let us now see how the LambdaTest Selenium Grid cloud can efficiently execute your tests across different system configurations.

Implementing Selenium sendKeys On LambdaTest Grid

It is highly likely that you have to run your automation suite across multiple browsers and OS configuration. LambdaTest Grid provides you an easy solution to execute your tests across multiple combinations by leveraging capabilities. These capabilities can be generated directly from the LambdaTest capabilities generator and integrated into your Selenium test.

Note that we will use the same example used above for execution on LambdaTest Grid cloud for one browser, but you can use the same test to perform cross browser testing by changing the capabilities and using Data Provider, as explained in our article on parallel testing.

package sendkeys;
import java.awt.AWTException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class SendkeysTest {


              public String username = "--- your user name ---";
              public String accesskey = "--- your access key ---";
              public static RemoteWebDriver driver = null;
              public String gridURL = "@hub.lambdatest.com/wd/hub";
              boolean status = false;
       //Method to set up the browser and open the dummy website
       @BeforeClass
       public void setUp() {

              DesiredCapabilities capabilities = new DesiredCapabilities();
              capabilities.setCapability("browserName", "chrome");
              capabilities.setCapability("version", "81.0");
              capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will get any available one
              capabilities.setCapability("build", "LambdaTestProject");
              capabilities.setCapability("name", "LambdaTestSendKeysProject");
              capabilities.setCapability("network", true); // Enables network logs
              capabilities.setCapability("visual", true); // Enables step by step screenshot
              capabilities.setCapability("video", true); // Enables video recording
              capabilities.setCapability("console", true); // Captures console logs
              try {
              driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
              } catch (MalformedURLException e) {
              System.out.println("Invalid grid URL");
              } catch (Exception e) {
              System.out.println(e.getMessage());
              }
              driver.get("https://www.lambdatest.com");
       }

       @Test
       public void testSendkeys() throws AWTException {


              //Locate the email and use sendkeys to pass the email to the field

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


              //Locate the Start Free Testing button and click it
              driver.findElement(By.xpath("//*[@id='testing_form']//button")).click();


       }


       @AfterClass
       public void burnDown() {
              driver.quit();
       }

}

You may change the capabilities settings as per your requirements and execute the test. You will see that the LambdaTest platform provides you a beautiful user interface of the test results, including a video of the execution. You can find these results under the Automation Logs tab in the Automation dashboard as shown below-

Automation dashboard

See how seamless Selenium automation can be by leveraging the capabilities of LambdaTest Grid cloud? Now, go ahead and try running a test case of your own that uses the sendKeys() method and leverages the capabilities of LambdaTest.

Conclusion

  • We understood what the Selenium sendKeys() method is and how it can be used in Selenium automation.
  • We saw how the clear() method could be used to clear off any string that is already present or entered in a text field.
  • We then saw how we could use the JavaScriptExecutor to enter text or string in a text field if we do not use the sendKeys() method.
  • Finally, we ran our test on the LambdaTest Grid, which helps us execute our tests in parallel across 2000+ browsers and operating systems.

We hope you found this article informative; we would love to hear what you think. Don’t forget to leave your comments below.

Happy Testing!