In the article about Actions Class in Selenium, nosotros discussed that Selenium provides a feature to handle keyboard events where user gestures can emulate. For example, suppose you search "India" on google search engine. For this, you volition blazon "India " and press the Enter fundamental, so that you meet the result queries. Say, yous want to automate this google search using the Selenium exam, how will you lot simulate pressing the ENTER fundamental using selenium lawmaking? The provision of the adequacy to simulate such keyboard actions is by the keyboard events generated using the Actions form of Selenium WebDriver. In this tutorial, nosotros will comprehend the details of all the Keyboard events supported by Selenium. Additionally, nosotros will too meet how Deportment course fit for the need of simulating the keyboard events in Selenium.

  • What are keyboard events in Selenium?
  • Why is Deportment form needed to perform Keyboard actions using Selenium WebDriver?
  • What is Actions Course in Selenium WebDriver?
  • What are the different methods provided by the Actions class for Keyboard Events?
  • How to handle contiguous Keyboard Actions using Actions Class?

What are keyboard events in Selenium?

A Keyboard Outcome describes a user's interaction with the keyboard. When a user presses single or multiple keys, keyboard events generate. Selenium provides various ways to automate these Keyboard Events, a few of which are:

  • Automate keyboard events using the sendKeys() method of WebElement form.
  • Automate keyboard events using Robot class.
  • And Automate keyboard events using Deportment course.

We already discussed the get-go two ways of handling the keyboard events using the "sendKeys()" method of WebDriver's WebElement course and "Robot class" in the manufactures given by corresponding links. In this article, we volition specifically embrace the details of the "Actions " class in Selenium WebDriver. Before going deep to sympathize the concepts of the "Actions " class, allow's first sympathize why specifically "Actions " class is needed to handle those Keyboard Events?

Why is Actions class needed to perform Keyboard actions using Selenium WebDriver?

When we interact with a web awarding, at that place volition be various scenarios when the user performs the post-obit actions:

  • Type in uppercase/Camel example letters: Wherever user demand to type a word or alphabetic character in caps, he/she will press the "SHIFT" key and will blazon the necessary characters, and any characters volition type while pressing the "SHIFT" cardinal, volition type every bit a uppercase letter.
  • Copy & Paste Text: When we demand to copy some text from i text box to another, we select the text past pressing "CTRL+A" they copy the text using "CTRL+C" and paste the text in the new text box by only clicking in the text box and pressing keys "CTRL+V" .

These are very common user deportment, which we perform on an almost daily footing. Now, as we discussed, Selenium WebDriver provides two ways to send any keyboard event to a web element:

  • sendKeys() method of WebElement class.
  • Actions class

At present let's try to empathize in item that if we desire to automate the scenario as mentioned in a higher place of typing the letters in the capital (with SHIFT key pressed ), using the sendKeys() method of the WebElement form.

Consider the following scenario for rapidly agreement the beliefs:

  • First, navigate to "https://demoqa.com/text-box."
  • Secondly, enter the Full proper name: "Mr.Peter Haynes".
  • Thirdly, enter the Email: "[email protected]"
  • After that, Enter the Electric current Address: "43 School Lane London EC71 9GO" .
  • Fifthly, click on the Current Address text box and Copy the Electric current Address.
  • After that, paste the copied address in the Permanent Accost text box.
  • Finally, validate that the text in the Current Address and Permanent Address is the same.

Let's try to automate the higher up scenario using the sendKeys() method of the WebElement class:

                      package            automationFramework;            import            static            org.junit.Assert.assertEquals;            import            org.openqa.selenium.Past;            import            org.openqa.selenium.Keys;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            public            class            KeyboardEvents            {            public            static            void            chief            (Cord[] args)            {            // Initialize ChromeDriver            // Hither we assume that the ChromeDriver path has been set in the Organisation Global variables            WebDriver driver=new            ChromeDriver();            //Navigate to the demo site            commuter.become("https://demoqa.com/text-box");            // Enter the Full Name            WebElement            fullName            =            driver.findElement(Past.id("userName"));         fullName.sendKeys("Mr.Peter Haynes");            //Enter the Email            WebElement email=commuter.findElement(By.id("userEmail"));         email.sendKeys("[email protected]");            // Enter the Current Address            WebElement currentAddress=driver.findElement(Past.id("currentAddress"));         currentAddress.sendKeys("43 School Lane London EC71 9GO");            // Copy the Current Accost            currentAddress.sendKeys(Keys.CONTROL);         currentAddress.sendKeys("A");         currentAddress.sendKeys(Keys.Control);         currentAddress.sendKeys("C");            //Press the TAB Key to Switch Focus to Permanent Address            currentAddress.sendKeys(Keys.TAB);            //Paste the Accost in the Permanent Accost field            WebElement permanentAddress=driver.findElement(By.id("permanentAddress"));         permanentAddress.sendKeys(Keys.Command);         permanentAddress.sendKeys("V");            //Compare Text of current Address and Permanent Address            assertEquals(currentAddress.getAttribute("value"),permanentAddress.getAttribute("value"));                  commuter.close();  	} }                  

In the above code snippet, though the sendKeys() method of WebElementallows using the Control Fundamental, information technology cannot practise the re-create and paste action, as it fails to combine the central sequences.

As we can encounter from the following screenshot, instead of pasting the content of Current Address in the Permanent Address text field, it just pasted the character "V".

sendKeys method of WebElement class

Every bit is clear from the above screenshot, that the text of the Electric current Accost text field did not copy to the Permanent Address text field, then it leads to failure of the exclamation when the comparing of the text of these two fields happens. So, when we execute the above test, it fails with the following error message:

Selenium Error message when text is not copied successfully using sendKeys method of WebElement Class

So, this is where the sendKeys() method of the WebElement course fails. In other words, it fails when we need to combine special keys such as "SHIFT" , "Command" , etc. with the different key sequences, which we all know, is a prevalent scenario when nosotros as a user are using any of the web applications.

Therefore, this is where the Actions class of Selenium WebDriver comes into the film, which provides diverse methods to specifically handle operations of these meta keyboard keys, which need to printing while performing operations on the other keyboard keys. Let'south see how we can handle such keyboard actions, using the Actions class of Selenium WebDriver.

What is Actions Grade in Selenium WebDriver?

As we discussed in a higher place, Selenium WebDriver provides a form named "Deportment" , which provides various methods that can help in automating and simulating the Keyboard and Mouse deportment. The beneath effigy shows the exhaustive list of methods offered past Selenium Web Driver, and the highlighted ones are the most used methods for simulating the Keyboard actions:

Methods for keyboard events provided by Actions Class in Selenium WebDriver

Let'south sympathize the Keyboard specific methods provided past the Actions Form:

What are the different methods provided by the Actions class for Keyboard Events?

As highlighted in the to a higher place screenshot, the Actions form majorly provide the post-obit three methods for simulating the Keyboard events:

  1. sendKeys(): This method sends a series of keystrokes to a given spider web element. This method has two overloaded formats:
  • sendKeys(CharSequence... KeysToSend): The post-obit screenshot shows the syntactical details of this method:

keyboard events: sendKeys() method in Actions class of Selenium WebDriver

This method sends a sequence of keys to a currently focused web chemical element, i.e., if we want to send specific characters to a web chemical element, that element must be first focussed, then merely the mentioned characters will go to that web element.

  • sendKeys(WebElement chemical element, CharSequence... KeysToSend): The following screenshot shows the syntactical details of this method:

Overloaded sendKeys method of Actions Class

This implementation of the sendKeys() method sends a sequence of characters/keys to a specific web element, which passes every bit the outset parameter to the method. This method starting time focuses on the target spider web chemical element and then performs the same action every bit sendKeys(CharSequence keys).

  1. keyDown(): This method simulates a keyboard activity when a specific keyboard key needs to printing. So, whenever you need to printing a key and and so perform specific other deportment, we can use the keyDown() method to keep the key pressed. E.g., say a user has to type some characters in Capital. So to simulate user beliefs, where the user presses the SHIFT   fundamental and so presses the set of characters that need to blazon in Capital. This method is also available in the following two overloaded variants:
  • keyDown(CharSequence fundamental): The following screenshot shows the syntactical details of this method:

keyboard events keyDown method of Actions class in Selenium WebDriver

This method presses the specified key on the currently focussed Web Element. This method generally presses the "Modifier keys" such equally SHIFT, CTRL, etc. If you want to press the keyboard key on a specified web element, so that spider web element kickoff needs to exist focussed explicitly, and and then this method needs to be invoked.

  • keyDown(WebElement element, CharSequence key): The following screenshot shows the syntactical details of this method:

Overloaded keyDown method of Actions class in Selenium WebDriver

This method kickoff focusses on the web element, which has been passed as a parameter to the method and presses the mentioned fundamental on that Spider web Element.

  1. keyUp(): We use this method majorly in collaboration with the keyDown() method. The keyboard fundamental which presses using the keyDown() method, doesn't go released automatically, so the aforementioned demand to be explicitly released using the keyUp() method. So, similar to the keyDown() method, this method has two overloaded variants:
  • keyUp(CharSequence primal): The following screenshot shows the syntactical details of this method:

keyboard events keyUp method of Actions class in Selenium WebDriver

This method releases the specified key on the currently focussed Web Element. If you want to release the keyboard key on a specified web element, and then that web element beginning needs to be focussed explicitly, and and then this method needs to be invoked.

  • keyUp(WebElement element, CharSequence key): The following screenshot shows the syntactical details of this method:

Overloaded keyUp method of Actions class in Selenium WebDriver

This method first focusses on the spider web element, which gets passed as a parameter to the method. So, it releases the mentioned primal on that Spider web Element.

Conclusively, we are articulate about all the keyboard specific methods provided by the Deportment class. Subsequently, let'southward see how we can automate the user as mentioned above scenario using the methods provided by the Actions form of Selenium WebDriver.

Let'southward change the above-written lawmaking-snippet to use the methods of Actions class, instead of using the methods of WebElement class:

                      package            automationFramework;            import            static            org.junit.Assert.assertEquals;            import            org.openqa.selenium.By;            import            org.openqa.selenium.Keys;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            import            org.openqa.selenium.interactions.Actions;            public            class            KeyboardEventsUsingActions            {            public            static            void            principal            (String[] args)            {            // Initialize ChromeDriver            // Here we assume that the ChromeDriver path has been set in the System Global variables            WebDriver commuter=new            ChromeDriver();            //Navigate to the demo site            driver.become("https://demoqa.com/text-box");            //Create object of the Actions class            Actions            actions            =            new            Deportment(driver);            // Enter the Total Name            WebElement            fullName            =            driver.findElement(Past.id("userName"));         fullName.sendKeys("Mr.Peter Haynes");            //Enter the Email            WebElement email=driver.findElement(By.id("userEmail"));         email.sendKeys("[email protected]");            // Enter the Current Address            WebElement currentAddress=commuter.findElement(By.id("currentAddress"));                  currentAddress.sendKeys("43 School Lane London EC71 9GO");            // Select the Current Accost using CTRL + A            deportment.keyDown(Keys.CONTROL);         actions.sendKeys("a");         actions.keyUp(Keys.Command);         deportment.build().perform();            // Re-create the Current Accost using CTRL + C            actions.keyDown(Keys.CONTROL);         actions.sendKeys("c");         deportment.keyUp(Keys.CONTROL);         actions.build().perform();            //Press the TAB Key to Switch Focus to Permanent Accost            actions.sendKeys(Keys.TAB);         actions.build().perform();            //Paste the Address in the Permanent Address field using CTRL + V            actions.keyDown(Keys.Control);         actions.sendKeys("5");         actions.keyUp(Keys.CONTROL);         actions.build().perform();            //Compare Text of current Address and Permanent Address            WebElement permanentAddress=commuter.findElement(By.id("permanentAddress"));         assertEquals(currentAddress.getAttribute("value"),permanentAddress.getAttribute("value"));                           driver.close();  	}  }                  

When we run the higher up code snippet, we get a sample output, equally shown below:

Copy Paste Scenario using keyboard events in Actions class of Selenium WebDriver

Equally we can see in the higher up screenshot, copying of the address from the "Current Address " field to the "Permanent Address " field was successful. Few more than bespeak, which we should explicitly focus on the higher up code:

  • Whichever META central (Eg CONTROL in the above utilise case) we press using the keyDown() method, it must be released using the keyUp() method. Otherwise, it will remain pressed and can cause side-effects on the next line of code.
  • All the commands of the "Actions" class perform/ execute their operations when we invoke the "build()" and "perform()" methods. And so, each of the expected actions/commands should follow by these methods.
  • The higher up lawmaking will piece of work on the Windows platform simply, as the CTRL+C, etc., is only the Windows-specific operation. We can update the platform-specific keys when we need to run the same program on other platforms.

How to handle contiguous Keyboard Actions using Actions Class?

Equally noticed in the above sections, all the methods of the Actions class briefed above returns an object of the Actions class only. And so, this gives u.s. the flexibility of using the "Chaining of Methods" , where nosotros can social club all the method invocations specific to i operation in one line of code only.

Let'due south modify the above-written code to trim it down further. We will employ the Chaing of Methods  and will handle the various face-to-face Keyboard operations in a single go:

                      parcel            automationFramework;            import            static            org.junit.Assert.assertEquals;            import            org.openqa.selenium.By;            import            org.openqa.selenium.Keys;            import            org.openqa.selenium.WebDriver;            import            org.openqa.selenium.WebElement;            import            org.openqa.selenium.chrome.ChromeDriver;            import            org.openqa.selenium.interactions.Actions;            public            class            KeyboardEventsUsingActions            {            public            static            void            main            (String[] args)            {            // Initialize ChromeDriver            // Here we assume that the ChromeDriver path has been ready in the Organisation Global variables            WebDriver driver=new            ChromeDriver();            //Navigate to the demo site            driver.get("https://demoqa.com/text-box");            //Create object of the Deportment form            Deportment            actions            =            new            Deportment(driver);            // Enter the Total Name            WebElement            fullName            =            commuter.findElement(By.id("userName"));         fullName.sendKeys("Mr.Peter Haynes");            //Enter the Email            WebElement electronic mail=driver.findElement(By.id("userEmail"));         email.sendKeys("[electronic mail protected]");            // Enter the Electric current Address            WebElement currentAddress=driver.findElement(Past.id("currentAddress"));                  currentAddress.sendKeys("43 School Lane London EC71 9GO");            // Select the Current Address            actions.keyDown(Keys.Command).sendKeys("a").keyUp(Keys.Control).build().perform();            // Copy the Current Address            actions.keyDown(Keys.CONTROL).sendKeys("c").keyUp(Keys.Command).build().perform();            //Press the TAB Primal to Switch Focus to Permanent Address            actions.sendKeys(Keys.TAB).build().perform();            //Paste the Address in the Permanent Address field            actions.keyDown(Keys.CONTROL).sendKeys("v").keyUp(Keys.Control).build().perform();            //Compare Text of current Address and Permanent Address            WebElement permanentAddress=driver.findElement(By.id("permanentAddress"));         assertEquals(currentAddress.getAttribute("value"),permanentAddress.getAttribute("value"));                           driver.close();  	}  }                  

The above code-snippet will perform precisely the aforementioned functionality as was being briefed in the previous department. The simply difference betwixt the two is that this lawmaking looks more compact and easy to read. So, this way, we tin combine various methods of the Actions form. Additionally, we can simulate user behavior for different Keyboard actions.

Key Takeaways

  • Keyboard events are the events that whatever of the Keyboard keys generate.
  • Additionally, they are a must to simulate the user behavior while automating a web awarding using Selenium WebDriver
  • The Actions Course of Selenium WebDriver provides - sendKeys(),keyUp(),keyDown() methods to handle diverse keyboard actions
  • The modifier cardinal is never released implicitly later on the keyDown() method - either we should call the keyUp(theKey) or sendKeys(Keys.Zero) to release the modifier.