Actions in Selenium


In Web driver, handling keyboard events and mouse events are done using the advanced user interactions API.
To perform action events, we need to use org. openqa.selenium.interactions.Actions class.

Create a Instance of Actions class
Actions action = new Actions(driver);

// to click on element
Action.moveToElement(element).click.perform

Perform method is used to execute the action. There are 2 types of actions: Keyboard and Mouse actions.


Below is the Sample code for Mouse action Events

packageactionsexp;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
importorg.openqa.selenium.interactions.Actions;
publicclass actionexp1 {
publicstaticvoidmain(String args[]){
WebDriver driver;
driver=newFirefoxDriver();
driver.get("http://www.istqb.in/");
driver.manage().window().maximize();
Actions action = new Actions(driver);
WebElementelement =driver.findElement(By.xpath("//*[@id='Mod164']/div[@class='moduletable-inner clearfix']/div[@class='ja-box-ctclearfix']/ul//a[@ href='/index.php/istqb-foundation/procedure']"));
// To click on the element
action.moveToElement(element).click().perform();
String title=driver.getTitle();
System.out.println("Title -->"+title);
}// main end
}//class end

In the above example ‘ movetoElement’ method is used to Moves the mouse to the middle of the element.

Series of multiple actions-using Build
Generates a composite action containing all actions so far, ready to be performed.'build()' method is used to compile all the list of actions into a single step and ready to be performed.

Below is the sample code for Build and Keyboard actionEvents

packageactionsexp;
importjava.util.concurrent.TimeUnit;
importorg.openqa.selenium.By;
importorg.openqa.selenium.Keys;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
importorg.openqa.selenium.interactions.Action;
importorg.openqa.selenium.interactions.Actions;
publicclass buildexp1 {
publicstaticvoidmain(String args[]) throwsInterruptedException{
WebDriver driver;
driver=newFirefoxDriver();
driver.get("http://www.istqb.in/");
driver.manage().window().maximize();
Actions builder = new Actions(driver);
WebElement element =driver.findElement(By.xpath("//*[@href='/index.php/contact-us1']"));
builder.moveToElement(element).click().perform();
Thread.sleep(2000);
WebElementele =driver.findElement(By.xpath("//*[@name='_ba4e46398a59ea65ee8de5490b4a6ab9' and @title='First Name' and @value='First Name']"));
Action multiple=(Action) builder
.moveToElement(ele)
.click()
// type the values in Capital Letters
.keyDown(ele,Keys.SHIFT)
.sendKeys("istqb")
.keyUp(ele,Keys.SHIFT)
.contextClick(ele)
.build();
multiple.perform();
}
}

There are few more most commonly used keyboard and mouse events provided by the Actions class.
KeyDown

KeyDown: Performs a modifier key press. Does not release the modifier key - subsequent interactions may assume it's kept pressed. Note that the modifier key is never released implicitly - either keyUp(theKey) or sendKeys(Keys.NULL) must be called to release the modifier.s
keyDown(Keys theKey)
theKey - Either Keys.SHIFT, Keys.ALT or Keys.CONTROL. If the provided key is none of those, IllegalArgumentException is thrown.
Ex:
Actions action=new Actions(driver)
Action.KeyDown(KEYS.SHIFT)

keyDown(WebElement element, Keys theKey)
Performs a modifier key press after focusing on an element. Equivalent to: Actions.click(element).sendKeys(theKey);
Parameters:
theKey - Either Keys.SHIFT, Keys.ALT or Keys.CONTROL. If the provided key is none of those, IllegalArgumentException is thrown.
element - WebElement to perform the action
Ex:
WebElement element =driver.findElement(By.xpath("//*[@name='_ba4e46398a59ea65ee8de5490b4a6ab9' and @title='First Name' and @value='First Name']"));
Actions action=new Actions(driver)
Action.KeyDown(element ,KEYS.SHIFT)

keyUp


keyUp(Keys theKey)

Performs a modifier key release. Releasing a non-depressed modifier key will yield undefined behaviour.
Parameters:
theKey - Either Keys.SHIFT, Keys.ALT or Keys.CONTROL.

keyUp(WebElement element, Keys theKey)
Performs a modifier key release after focusing on an element. Equivalent to: Actions.click(element).sendKeys(theKey);
Parameters:
theKey - Either Keys.SHIFT, Keys.ALT or Keys.CONTROL.
element - WebElement to perform the action on
Ex: action.keyUp(element,Keys.SHIFT)

sendKeys


sendKeys(java.lang.CharSequence... keysToSend)
Sends keys to the active element. This differs from calling WebElement.sendKeys(CharSequence...) on the active element in two ways:
The modifier keys included in this call are not released.
There is no attempt to re-focus the element - so sendKeys(Keys.TAB) for switching elements should work.
Parameters:
keysToSend - The keys.




sendKeys(WebElementelement,java.lang.CharSequence... keysToSend)
Equivalent to calling: Actions.click(element).sendKeys(keysToSend). This method is different from WebElement.sendKeys(CharSequence...).
Parameters:
element - element to focus on.
keysToSend - The keys.

clickAndHold


clickAndHold(WebElementonElement)

Clicks (without releasing) in the middle of the given element. This is equivalent to: Actions.moveToElement(onElement).clickAndHold()
Parameters:onElement - Element to move to and click.

clickAndHold()
Clicks (without releasing) at the current mouse location.

Release


release(WebElementonElement)
Releases the depressed left mouse button, in the middle of the given element. This is equivalent to: Actions.moveToElement(onElement).release() Invoking this action without invoking clickAndHold() result in undefined behaviour.
Parameters:onElement - Element to release the mouse button above.
release()
Releases the depressed left mouse button at the current mouse location.

Click

click(WebElementonElement)
Clicks in the middle of the given element. Equivalent to Actions.moveToElement(onElement).click()
Parameters:onElement - Element to click.

click()
Clicks at the current mouse location. Useful when combined with moveToElement(org.openqa.selenium.WebElement, int, int) or moveByOffset(int, int).

doubleClick

doubleClick(WebElementonElement)
Performs a double-click at middle of the given element. Equivalent to: Actions.moveToElement(element).doubleClick()
Parameters:onElement - Element to move to.

doubleClick()
Performs a double-click at the current mouse location.

moveToElement

moveToElement(WebElementtoElement)
Moves the mouse to the middle of the element. The element is scrolled into view and its location is calculated using getBoundingClientRect.
Parameters:toElement - element to move to.

moveToElement(WebElementtoElement, intxOffset, intyOffset)
Moves the mouse to an offset from the top-left corner of the element. The element is scrolled into view and its location is calculated using getBoundingClientRect.
Parameters:
toElement- element to move to.
xOffset- Offset from the top-left corner. A negative value means coordinates left from the element.
yOffset- Offset from the top-left corner. A negative value means coordinates above the element.

moveByOffset

moveByOffset(intxOffset,intyOffset)
Moves the mouse from its current position (or 0,0) by the given offset. If the coordinates provided are outside the viewport (the mouse will end up outside the browser window) then the viewport is scrolled to match. if the provided offset is outside the document's boundaries, it will throwsMoveTargetOutOfBoundsException
Parameters:
xOffset - horizontal offset. A negative value means moving the mouse left.
yOffset - vertical offset. A negative value means moving the mouse up.

contextClick

contextClick(WebElementonElement)
Performs a context-click at middle of the given element. First performs a mouseMove to the location of the element.
Parameters:onElement - Element to move to.

contextClick()
Performs a context-click at the current mouse location.

dragAndDrop

dragAndDrop(WebElement source, WebElement target)
A convenience method that performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.
Parameters:
source - element to emulate button down at.
target - element to move to and release the mouse at.

dragAndDropBy

dragAndDropBy(WebElementsource,intxOffset, intyOffset)
A convenience method that performs click-and-hold at the location of the source element, moves by a given offset, then releases the mouse.
Parameters:
source - element to emulate button down at.
xOffset - horizontal move offset.
yOffset - vertical move offset.

Pause(@Deprecated)
pause(long pause)
Deprecated. 'Pause' is considered to be a bad design practice.
Performs a pause.
Parameters:pause - pause duration, in milliseconds.

Build

build()
Generates a composite action containing all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to build() will contain fresh sequences).

perform
perform()
A convenience method for performing the actions without calling build() first.

Example for DragAndDropBy and ContextClick

Before executing the class


image

packageactionsexp;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
importorg.openqa.selenium.interactions.Actions;
publicclassdragexp {
publicstaticvoidmain(String args[]) throwsInterruptedException{
WebDriver driver;
driver = newFirefoxDriver();
driver.get("http://jqueryui.com/");
driver.manage().window().maximize();
Actions action =new Actions(driver);
WebElement element=driver.findElement(By.xpath("//*[@id='sidebar']/aside[1]/ul/li[1]/a[@href='http://jqueryui.com/draggable/']"));
action.moveToElement(element).click().perform();
WebElementmyframe = driver.findElement(By.xpath("//iframe[@class='demo-frame']"));
driver.switchTo().frame(myframe);
WebElement ele1=driver.findElement(By.xpath("//*[@id='draggable']"));
// DragAndDropBy-performs click-and-hold at the location of the source element, moves by a given offset, then releases the mouse.
action.dragAndDropBy(ele1, 100, 80).perform();
action.contextClick(ele1).perform();
}
}



After executing the class

image

Sample code forDragAndDrop

packageactionsexp;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
importorg.openqa.selenium.interactions.Actions;
publicclassdraganddrop {
publicstaticvoidmain(String args[]) throwsInterruptedException{
WebDriver driver;
driver = newFirefoxDriver();
driver.get("http://jqueryui.com/");
driver.manage().window().maximize();
Actions action =new Actions(driver);
WebElementelement=driver.findElement(By.xpath("//*[@id='sidebar']/aside[@class='widget']/ul/li[2]/a[@href='http://jqueryui.com/droppable/']"));
action.moveToElement(element).click().perform();
WebElementmyframe = driver.findElement(By.xpath("//iframe[@class='demo-frame']"));
driver.switchTo().frame(myframe);
WebElement drag=driver.findElement(By.xpath("//*[@id='draggable']"));
WebElement drop=driver.findElement(By.xpath("//*[@id='droppable']"));
// Drag and drop-performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.
action.dragAndDrop(drag, drop).perform();
}
}

Sample Code for ClickAndHold

packageactionsexp;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
importorg.openqa.selenium.interactions.Actions;
publicclassclickandholdexp {
publicstaticvoidmain(String args[]) throwsInterruptedException{
WebDriver driver;
driver = newFirefoxDriver();
driver.get("http://jqueryui.com/");
driver.manage().window().maximize();
Actions action =new Actions(driver);
WebElement element=driver.findElement(By.xpath("//*[@id='sidebar']/aside[@class='widget']/ul/li[4]/a[@href='http://jqueryui.com/selectable/']"));
action.moveToElement(element).click().perform();
Thread.sleep(1000);
WebElementmyframe = driver.findElement(By.xpath("//iframe[@class='demo-frame']"));
driver.switchTo().frame(myframe);
WebElement cah1=driver.findElement(By.xpath("//*[@id='selectable']/li[1]"));
WebElementcah2=driver.findElement(By.xpath("//*[@id='selectable']/li[2]"));
// ClickAndHold -
//Clicks (without releasing) in the middle of the given element. This is equivalent to: Actions.moveToElement(onElement).clickAndHold()
action.clickAndHold(cah1).perform();
action.release(cah1).perform();
}
}




Sample code for KeyDown,KeyUp,SendKey,DoubleClick,ContextClick and Build

packageactionsexp;
importjava.util.concurrent.TimeUnit;
importorg.openqa.selenium.By;
importorg.openqa.selenium.Keys;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
importorg.openqa.selenium.interactions.Action;
importorg.openqa.selenium.interactions.Actions;
publicclass buildexp1 {
publicstaticvoidmain(String args[]) throwsInterruptedException{
WebDriver driver;
driver=newFirefoxDriver();
driver.get("http://www.istqb.in/");
driver.manage().window().maximize();
Actions builder = new Actions(driver);
WebElement element =driver.findElement(By.xpath("//*[@href='/index.php/contact-us1']"));
builder.moveToElement(element).click().perform();
WebElement ele=driver.findElement(By.xpath("//*[@name='_ba4e46398a59ea65ee8de5490b4a6ab9' and @title='First Name' and @value='First Name']"));
Action multiple=(Action) builder
.moveToElement(ele)
.click()
// type the values in Capital Letters
.keyDown(ele,Keys.SHIFT)
.sendKeys("istqb")
.keyUp(ele,Keys.SHIFT)
.doubleClick(ele)
.contextClick(ele)
.build();
multiple.perform();
}
}


Sample code for MoveOffSet

packageactionsexp;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
importorg.openqa.selenium.interactions.Actions;
publicclassMoveByOffsetexp {
publicstaticvoidmain(String args[]) throwsInterruptedException{
WebDriver driver;
driver = newFirefoxDriver();
driver.get("http://jqueryui.com/");
driver.manage().window().maximize();
Actions action =new Actions(driver);
WebElement element=driver.findElement(By.xpath("//*[@id='sidebar']/aside[@class='widget']/ul/li[3]/a[@href='http://jqueryui.com/resizable/']"));
action.moveToElement(element).click().perform();
WebElementmyframe = driver.findElement(By.xpath("//iframe[@class='demo-frame']"));
driver.switchTo().frame(myframe);
WebElement move1=driver.findElement(By.xpath("//*[@id='resizable']"));
// MoveByOffSet -Moves the mouse from its current position (or 0,0) by the given offset. If the coordinates provided are outside the viewport (the mouse will end up outside the browser window) then the viewport is scrolled to match.
action.clickAndHold(move1).moveByOffset(70, 70).release().build().perform();
}
}



Sample code for multiple Selection
Let’s select 4 items from the list
See the below picture
image

packageactionsexp;
importorg.openqa.selenium.By;
importorg.openqa.selenium.Keys;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
importorg.openqa.selenium.interactions.Action;
importorg.openqa.selenium.interactions.Actions;
publicclassmultiselectexp {
publicstaticvoidmain(String args[]) throwsInterruptedException{
WebDriver driver;
driver = newFirefoxDriver();
driver.get("http://jqueryui.com/");
driver.manage().window().maximize();
Actions action =new Actions(driver);
WebElement element=driver.findElement(By.xpath("//*[@id='sidebar']/aside[@class='widget']/ul/li[4]/a[@href='http://jqueryui.com/selectable/']"));
action.moveToElement(element).click().perform();
WebElementmyframe = driver.findElement(By.xpath("//iframe[@class='demo-frame']"));
driver.switchTo().frame(myframe);
WebElement cah1=driver.findElement(By.xpath("//*[@id='selectable']/li[1]"));
WebElement cah2=driver.findElement(By.xpath("//*[@id='selectable']/li[2]"));
WebElement cah3=driver.findElement(By.xpath("//*[@id='selectable']/li[6]"));
WebElement cah4=driver.findElement(By.xpath("//*[@id='selectable']/li[7]"));
Actionact=action.keyDown(Keys.CONTROL).click(cah1).click(cah2).click(cah3).click(cah4).build();
act.perform();
}
}

Comments