Actions and Action Classes used to handle the keyboard and mouse events. These are the inbuilt features of the Selenium library.
Methods in WebDriver object
Normally, we can handle few events via WebDriver object like click(), clear(), and sendKeys() as mentioned below:
- click() : To Left click on any web-element to activate it.
- clear(): To delete all the content from a text field.
- sendKeys(): To pass any key via keyboard or to type in a text field.
Code Example
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
String googleURL="https://www.google.com/"; driver.get(googleURL);
By searchXpath=By.name("q");
// Normal methods in WebDriver for input (Keyboard/Mouse)
// Click on Search text field
driver.findElement(searchXpath).click();
//Type text in lower case
driver.findElement(searchXpath).sendKeys("computer");
//Type text in lower case
driver.findElement(searchXpath).sendKeys(Keys.SHIFT+"computer");
// We can press any key via keyboard as below we are uing Enter key. driver.findElement(searchXpath).sendKeys(Keys.ENTER);
// To clear text from the Text field.
//driver.findElement(searchXpath).clear();
}
Actions and Action Classes
But there are scenarios where we have to use Events like Right-click via Mouse, Drag and Drop, Mouse Hover, Double click, Keyboard Keypress, Key release, sending keys to a text field. We can handle all these via Actions and Action Classes.
Steps to use Actions and Action Classes
- First, we have to create an object of the Actions class and associate it with the WebDriver Object.
- Then we have to call required methods via Actions or Action object.
- Now, call the build() method to create a chain of multiple actions or methods.
- In the end, we have to call perform() to execute the chain of multiple actions that we have created via build().
In this blog, will learn basic methods from Actions and Action classes.
Method | Feature |
moveToElement(element) | To mouse hover over any element to view tooltip text. |
contextClick(element) | To right-click on any element. |
sendKeys(String) | To type content in the text field. |
doubleClick(element) | Double click to select text. |
keyDown(Keys.SHIFT) | To press any modifier key like Control, Shift, etc. |
dragAndDrop(sourceOption, destHolder) | To perform Drag and drop activity. |
clickAndHold(element) | Click on any element and Hold to drag. |
release() | To release any element. |
Mouse Hover over a web element
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String googleURL = "https://www.google.com/";
driver.get(googleURL);
By searchXpath = By.name("q");
WebElement element=driver.findElement(searchXpath);
Actions actions=new Actions(driver);
//Mouser Hover over element
Action mouseHover= actions.moveToElement(element).build();
mouseHover.perform();
}
Right Click on a web element
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String googleURL = "https://www.google.com/";
driver.get(googleURL);
Actions actions=new Actions(driver);
// Right-click via mouse
WebElement googleLogo=driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/img"));
Action rightClick=actions.contextClick(googleLogo)
.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER).build();
rightClick.perform();
// if .sendKeys(Keys.ARROW_DOWN) doesn't work we can use Robot class as below.
Robot robot=new Robot(); robot.keyPress(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
}
Type text in the text field
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String googleURL = "https://www.google.com/";
driver.get(googleURL);
By searchXpath = By.name("q");
WebElement element=driver.findElement(searchXpath);
Actions actions=new Actions(driver);
// Type text in search field
Action textEntry=actions.keyDown(element,Keys.SHIFT)
.sendKeys("computer")
.sendKeys(Keys.ENTER)
.build();
textEntry.perform();
}
Double Click to select content in text field
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String googleURL = "https://www.google.com/";
driver.get(googleURL);
By searchXpath = By.name("q");
WebElement element=driver.findElement(searchXpath);
Actions actions=new Actions(driver);
// Type text in search field
Action textEntry=actions.keyDown(element,Keys.SHIFT)
.sendKeys("computer")
.sendKeys(Keys.ENTER)
.build();
textEntry.perform();
WebElement newSearchField=driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div[1]/div[2]/div/div[2]/input"));
Action doubleClick=actions.doubleClick(newSearchField)
.build();
doubleClick.perform();
}
Long press of any Modifier Key
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String googleURL = "https://www.google.com/";
driver.get(googleURL);
By searchXpath = By.name("q");
WebElement element=driver.findElement(searchXpath);
Actions actions=new Actions(driver);
// Long Press of any Modifier key via Keypress method
// Here we long press SHIFT key to type in upper case
Action longpress=actions.keyDown(element, Keys.SHIFT)
.sendKeys("india")
.sendKeys(Keys.SPACE)
.sendKeys("delhi")
.sendKeys(Keys.SPACE)
.keyUp(Keys.SHIFT)
.sendKeys(Keys.SPACE)
.sendKeys("mumbai")
.build();
longpress.perform();
}
Drag and Drop
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String w3SURL="https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop";
driver.get(w3SURL);
driver.switchTo().frame("iframeResult");
WebElement sourceOption=driver.findElement(By.xpath("//*[@id=\"drag1\"]"));
WebElement destHolder=driver.findElement(By.xpath("//*[@id=\"div1\"]"));
System.out.println(sourceOption.getAttribute("src"));
System.out.println(destHolder.getAttribute("ondrop"));
Actions actions=new Actions(driver);
actions.clickAndHold(sourceOption).build().perform();
actions.moveToElement(destHolder).build().perform();
actions.release().build().perform();
// We can also use dragAndDrop method from actions class
//actions.dragAndDrop(sourceOption, destHolder).build().perform();
System.out.println("completed");
}
Selenium Tutorials:
- Selenium-12 || Select Class to handle drop-down.
- Selenium-11 || Use of Actions and Action Classes.
- Selenium-10 || Taking Screenshots using Selenium
- Selenium-9 || Understanding WebDriver API.
- Selenium-8 || Implementing Wait(s) in Selenium.
- Selenium-7 || Let’s learn to create complex XPath.
- Selenium-6 || XPath is the best way to locate web elements.
- Selenium-5 || Locating web elements using various type of Locators.
- Selenium-4 || Handling multiple web browsers.
- Selenium-3 || First program using Selenium Web Driver.
- Selenium-2 || Let’s learn Selenium IDE.
- Selenium-1 || Understanding Selenium and Selenium WebDriver.
- TestNG – 1 || Introduction and benefits of TestNG Framework.
- TestNG – 2 || Installation process and a sample program of TestNG.
- TestNG – 3 || Create and execute multiple Test Cases.
- TestNG – 4 || Let’s understand @Test Annotation and attributes.
- TestNG – 5 || Understand Assertion in TestNG.
- TestNG – 6 || Use of @BeforeMethod and @AfterMethod.
- TestNG – 7 || Use of @BeforeClass and @AfterClass.
- TestNG – 8 || Creation and execution of Test Suites.
- TestNG – 9 || Let’s move deep into the Test Suites.
- TestNG – 10 || Use @BeforeTest and @AfterTest Annotations.
- TestNG – 11 || Groups attribute with @Test Annotation.
- TestNG – 12 || Use of @BeforeGroups & @AfterGroups.
- TestNG – 13 || Use of @BeforeSuite & @AfterSuite.
- TestNG – 14 || DataProvider annotation & attribute.
- TestNG – 15 || DataProvider with parameters.
- TestNG – 16 || Access data from Excel sheet using DataProvider.
- TestNG – 17 || Passing multiple Parameters in testng xml.
- TestNG – 18 || Multiple Browser and Parallel Execution in TestNG.
- TestNG -19 || Concept of Parallel Execution.
- TestNG – 20 || Run TestNG Program using main() method.
- Computer Basics -1 || Introduction and Structure of Computer.
- Computer Basics -2 || Types of Computers and Usage.
- Computer Basics -3 || What are the different types of Software?
- Computer Basics -4 || Importance of Operating System(OS).
- Computer Basics -5 || Understanding of Number System.
- Computer Basics -6 || Understanding MS-DOS Commands.
- Computer Basics -7 || Important Features of MS-Word.
- Computer Basics -8 || Let’s learn the usage of MS-Excel.
- Computer Basics -9 || Understand and Implement Data Validation in Excel.
- Computer Basics -10 || How to apply Filter in a data set in Excel?
- Computer Basics -11 || Using Charts in place of Data Tables in Excel.
- Computer Basics -12 || Advantages of PivotCharts over Simple Charts in Excel.
- Computer Basics -13 || Creating pivot charts/tables in Excel.
- Abbreviations to Full-Forms in Computer Basics.
- Basic Java – 1 || Understand Java before start learning JAVA.
- Basic Java – 2 || Variables and Data Types used in JAVA.
- Basic Java – 3 || Understanding Class, Objects, Methods in Java.
- Basic Java – 4 || More on methods(Return Type and Parameters)
- Basic Java – 5 || Methods- Call by Value and Call by Reference in Java.
- Basic Java – 6 || Understanding of Constructor and Destructor in JAVA.
- Basic Java – 7 || Static Variables and Methods.
- Basic Java – 8 || Lets learn about Arrays in Java.
- Basic Java – 9 || Performing multiple operations using Java Operators.
- Basic Java – 10 || Conditions (If and Switch) in JAVA.
- Basic Java – 11 || for and for-each in Java. (Loops Part-1)
- Basic Java – 12 || Alternate looping concepts while and do-while. (Loops Part-2)
- Basic Java – 13 || Decimal values v/s Octal base(8) values in JAVA.
- Basic Java – 14 || Learn about String literals in Java.
- Basic Java – 15 || Runtime User Input using Scanner Class (Part-1).
- Basic Java – 16 || Runtime User Input using BufferedReader Class (Part-2).
- Basic Java – 17 || Runtime User Input using Console Class (Part-3).
- Basic Java – 18 || Difference between break and continue keywords.
- Basic Java – 19 || Sending Email using Java (Part-1).
- Basic Java – 20 || Sending Email with attachment using Java (Part-2).
- Basic Java – 21 || Stack memory and Heap memory in Java.
- Basic Java – 22 || Let’s learn more about String.
- Basic Java – 23 || String, StringBuffer & StringBuilder in Java.
- Basic Java – 24 || Exception Handling using Try Catch.
- Collection Types and features in Java. (Collection-1)
- Use of ArrayList Class in Java. (Collection-2)
- LinkedList Class implementation and usage. (Collection-3)
- Using HashMap in Java. (Collection-4)
- Using HashSet in Java. (Collection -5)
- File Handling | Reading data from word document(.doc or .docx) in JAVA.
- File Handling | Reading data from Excel files (.xls or .xlsx) using JAVA.
- File Handling | Writing data into an Excel(.XLSX or .XLS) File.
- File Handling | Implement formatting in Excel using Java.
- File Handling | Copy existing data from one workbook to another workbook in Java.
- File Handling | Reading data from PDF file using JAVA.
- File Handling || Traverse folders and subfolders in Java.
- File Handling || Reading and Writing data from a text file.
- File Handling || Multiple file creation using template based input data.
- Framework || Simple example of Key Driven Framework using excel sheet in Selenium(JAVA).
- QnA || How to use Constructors in Abstract class?
- QnA | Difference between Integer and int keywords.
- QnA | Can main method be overloaded?
- QnA | How do I reverse a String/Sentence in Java?
- QnA | Perform Multiplication and Division without * or / or % operators.
- QnA | How do I get the default value of data type?
- QnA | How to split String if it contains period symbol (.) in between?
- Different ways to Reverse a String in Java.
- Copy formatting & style of cells from one sheet to another.
- Getting IP address and Hostname using InetAddress Class.
- User inputs via Command Prompt using arguments of main() method of a class.
- Program for List and ArrayList in Java.
- Useful methods and implementation under Scanner Class.
- Swapping two variable values without using any third variable.
- Difference between int x= 10 and y=010 in Java.
- Parameterized Constructors v/s Setter and Getter function in JAVA.
- Override a Static Method.
- JIRA Tutorials-2 || Implement Search and Filter on JIRA Issues.
- JIRA Tutorials-1 || Basic understanding of JIRA.