Drag and Drop in Selenium WebDriver
Hi Friends, today we are going to learn how to perform Drag and Drop in selenium which is one of the common use cases in automation. In this tutorial, we are going to study the handling of drag and drop event in Selenium WebDriver using Actions class.
Actions in Selenium WebDriver
For performing a complex user gestures like drag and drop, we have a Actions class in Selenium WebDriver. Using the Actions class, we first build a sequence of composite events and then perform it using Action (an interface which represents a single user-interaction). The different methods of Actions class we will be using here are-
- clickAndHold(WebElement element) - Clicks a web element at the middle(without releasing).
- moveToElement(WebElement element) - Moves the mouse pointer to the middle of the web element without clicking.
- release(WebElement element) - Releases the left click(which is in pressed state).
- build() - Generates a composite action
Sample Code for performing drag and drop operation-
package learnSelenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class MouseOver {
public static void main(String[] args) throws InterruptedException{
WebDriver driver = new FirefoxDriver();
//Launching sample website
driver.get("www.samplesite.com");
driver.manage().window().maximize();
//Identify the WebElement on which drag and drop operation needs to be performed
WebElement fromWebElement = driver.findElement(By Locator of fromWebElement);
//Identify the WebElement to which the above object is dropped
WebElement toWebElement = driver.findElement(By Locator of toWebElement);
//Creating object of Actions class to build composite actions
Actions builder = new Actions(driver);
//Building a drag and drop operation
Action dragAndDrop = builder.clickAndHold(fromWebElement)
.moveToElement(toWebElement)
.release(toWebElement)
.build();
//Performing the drag and drop action
dragAndDrop.perform();
//Thread.sleep just for user to notice the event
Thread.sleep(3000);
//Closing the driver instance
driver.quit();
}
}
No comments:
Post a Comment