Drag and Drop in Selenium WebDriver

Drag and Drop in Selenium WebDriver

Drag and Drop is one of the common scenarios in automation. In this tutorial, we are going to study the handling of drag and drop events in Selenium WebDriver using the Actions class. For practice, you can check the dummy page having a draggable web element.

This is also one of the most common Selenium interview questions. So, even if you don’t normally encounter the requirement of automating drag and drop action still it is worth learning about it.

Actions in Selenium WebDriver

For performing 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 the pressed state).
  • build() – Generates a composite action.

Code snippet to perform Drag and Drop

Below is the code snippet for performing drag and drop operation-

//WebElement on which drag and drop operation needs to be performed
WebElement fromWebElement = driver.findElement(By Locator of fromWebElement);
//WebElement to which the above object is dropped
WebElement toWebElement = driver.findElement(By Locator of toWebElement);

//Creating an object of Actions class to build composite actions
Actions builder = new Actions(driver);

//Building drag and drop action
Action dragAndDrop = builder.clickAndHold(fromWebElement)
.moveToElement(toWebElement)
.release(toWebElement)
.build();
//Performing the drag and drop action
dragAndDrop.perform();

Write to us if you have any queries and share your views. Also please share this post with your friends and don’t forget to check our complete selenium tutorial.

selenium tutorial beginners

От QA genius

Adblock
detector