Testing With Selenium WebDriver (82 Blogs) Become a Certified Professional
AWS Global Infrastructure

Software Testing

Topics Covered
  • Testing With Selenium WebDriver (72 Blogs)
SEE MORE

How to Drag and Drop in Selenium?

Last updated on Sep 10,2024 104 Views

A passionate and knowledgeable tech enthusiast known for his expertise in the... A passionate and knowledgeable tech enthusiast known for his expertise in the world of technology and programming. With a deep-rooted passion for coding, Sarfaraz...

Drag-and-drop is one of the core skills that an automation tester must have in Selenium. This technique helps the developer imitate user interactions with web elements. Such testing is applied to complex interfaces and dynamic web applications.

For this reason, it is very crucial to understand how this functionality could be implemented for practical testing. We will go through the different principles and how to drag and drop in Selenium with Python and Java, with respective practical working examples.

 

What is Drag and Drop in Selenium?

Drag and drop in Selenium is a technique for moving web elements around a web page from one position to another. It emulates an end-user action of clicking the web element, holding the mouse button, moving to a new position, and releasing the button. This functionality is exercised in almost every modern web application to perform different functions, like moving items around, file upload, and interactive UI components.

Selenium, using its class Actions, intrinsically supports a drag-and-drop operation. This class of Selenium supports different methods to perform complex actions, which users usually take part in; one of them is drag and drop. Generally, the process tends to have three significant steps bound together:

  1. Identifying the source element: element that has to be dragged
  2. Identifying the target element: element where the source element will be dropped
  3. Performing the Drag and drop action using the Selenium application programming interface.

Drag and drop in Selenium, depending on the programming language one uses. For instance, drag and drop in Selenium Python would look quite different from Drag and drop in Selenium Java. However, the fundamental concept still holds across languages.

It is worth mentioning that how to perform drag-and-drop in selenium is susceptible and tricky to automate. They mainly require the correct timing and coordination between various mouse events. Moreover, some web applications specifically implement custom drag-and-drop behavior, which may not work with the earlier-mentioned standard methods that Selenium provides. In such cases, the JavaScript execution approach is necessary. If you want to learn more about how to handle drag and drop in Selenium, consider taking a Selenium Course or looking up resources on Selenium Tutorial.

 

Differences Between Drag and Drop and Action Class Build

While Drag and drop is a particular action, the Action Class in Selenium offers much more. Their differences may be further elaborated as below:

Drag and Drop

  • Specifically for moving elements from one place to another
  • Usually implemented as a single method call
  • Restricted only to drag-and-drop operations

Action Class

  • Offers many complex user interactions
  • Allows multiple actions to be chained
  • Click, holding, moving, releasing―methods exist for these and more

The Action Class is versatile and can be adjusted to create a series of custom actions. It can significantly help in more complex interactions than just a simple drag-and-drop series of actions. Knowing what Selenium is is a good thing.

 

Use case: Example of drag-and-drop action using the Java Selenium API.

Now, we will check out the practical example of handling Drag and drop in Selenium with Java. The following drag and drop example in Selenium is moving an element on a web page from one place to another.


import org. openqa. Selenium.By;

import org. openqa. Selenium.WebDriver;

import org. openqa. Selenium.WebElement;

import org. openqa. Selenium. Chrome.ChromeDriver;

import org. openqa. Selenium. Interactions.Actions;

public class DragAndDropExample {

public static void main(String[] args) {

<br data-mce-bogus="1">

//Setting up WebDriver

```

WebDriver driver = new ChromeDriver();

driver.get("https://example.com/dragdrop");

// Find source and target elements

WebElement sourceElement = driver.findElement(By.id("draggable"));

WebElement targetElement = driver.findElement(By.id("droppable"));

// Create an Action object

Actions actions = new Actions(driver);

//Drag and drop perform

actions.dragAndDrop(sourceElement, targetElement).perform();

// Verify the drag-and-drop operation

String droppedText = targetElement.getText();

if (droppedText.equals("Dropped!")) {

System.out.println("Drag and drop successfully done!");

} else {

System.out.println("Drag and drop not done successfully");

}

// Close the browser

driver.quit();

 

Drag And Drop By action in Selenium with OffSets

The dragAndDropBy() method achieves a more accurate and precise drag-and-drop operation. It moves an element by several pixels along the x and y axes. It is specifically helpful if one wants to drag an element not to the drop zone directly but to some area, which acts as a source for many other operations.

Following is how the dragAndDropBy() method works:


actions.dragAndDropBy(sourceElement, xOffset, yOffset).perform();

The parameters xOffset and yOffset indicate across which horizontal and vertical direction to move the element. Positive values move it to the right and downward, whereas negative values move it left and upward.

This method has the following uses:

  1. You can precisely position the slider controls to your specification several offset pixels in moving sliders.
  2. It is positioning an element where it must be placed on that page.
  3. Testing responsive designs: To test responsive behaviors, you can simulate dragging and dropping an element to various screen positions.
  4. Complex Drag and Drop: If the standard drag and drop operations between two elements aren’t enough.

Example with dragAndDropBy():


WebElement slider = driver.findElement(By.id("slider"));

Actions actions = new Actions(driver);

actions.dragAndDropBy(slider, 100, 0).perform();

The above code will slide some slider 100 pixels right.

There are some gotchas to take care of when dealing with dragAndDropBy():

  1. Your browser may slightly interpret the offsets differently differently from other browsers.
  2. Element is in view: Must be in the view and not covered by another element.
  3. Page is scrolled: You must scroll the page first to the target position.
  4. Performance: Big offsets might take more time to execute.
  5. Element dimensions: An element should consider its size when calculating offsets.

The following is a bit more complex example of dragging an element onto the page to a specific coordinate:


WebElement draggable = driver.findElement(By.id("draggable"));

Actions actions = new Actions(driver);

// Get current position of element

int startX = draggable.getLocation().getX();

int start = draggable.getLocation().getY();

// Calculate the farthest point to move (500, 300)

int offset = 500 - starts;

int offset = 300 - start;

// Perform drag and drop

actions.dragAndDropBy(draggable, xOffset, yOffset).perform();

This script will drag an element to coordinates (500, 300) of the page, regardless of its starting position.

During drag-and-drop operations, especially in automation testing, many exceptions and corner cases must be considered. For example, one may encounter the StaleElementReferenceException, where the page structure changes. One can overcome that by implementing retry logic or by using explicit waits on the elements so that they come into the state necessary for action execution.

Another critical factor is the cross-browser aspect. While Selenium tries to offer a consistent API across browsers, handling Drag and drop can be very different. Targeting cross-browser testing of your drag-and-dropDrag scripts is recommended to ensure consistent results.

You may have to combine a few actions to create more complex scenarios. For instance, this way, you could break down the Drag and drop operation over multiple statements to make the simulation more or less like the way a user would do it;


Actions actions = new Actions(driver);

actions.clickAndHold(sourceElement)

.moveToElement(targetElement)

.release()

.build()

.perform();

The syntax of Drag and drop in Selenium Python differs, but the concepts remain almost the same. Here is how you would probably execute drag and drop in Python:

From selenium import webdriver

From Selenium. webdriver. Everyday.action_chains import ActionChains


driver = webdriver.Chrome()

driver.get("https://example.com/dragdrop")

source = driver.find_element_by_id("draggable")

target = driver.find_element_by_id("droppable")

actions = ActionChains

The way to drag and drop in Selenium sometimes depends on the peculiarities of the web application you’re testing. Some sites use custom JavaScript implementations on drag-and-drop functionality, but they do not respond to standard methods invoked by Selenium. In such cases, you can sometimes use scripting to simulate the Drag and Drag action directly:


String script = "function simulate(f,c,d,e){

"var b, a = null;" +

"for (b in eventMatchers) {" +

"a = eventMatchers[b];" +

"if (a.test(c)) {" ) +

" return f(a.run(c, d, e));" ) +

"}"

"}" +

 

"};" +

"var eventMatchers={" +

"'HTMLEvents':/^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/",

+" 'MouseEvents':/^(?:click|dblclick|mouse(?:down|up|over|move|out))$/}";

+" simulate(function(e,f,g){

"var d=e.ownerDocument||document;" +

"var b=d.createEvent('MouseEvents');" +

"b.initMouseEvent(f,true,true,d.defaultView,0,g.screenX,g.screenY,g.clientX,g.clientY,false,false,false,false,0,null);

"e.dispatchEvent(b);" +

"},arguments[0],arguments[1],arguments[2])";

 

((JavascriptExecutor) driver).executeScript(script, sourceElement, "mousedown", 0);

((JavascriptExecutor) driver).executeScript(script, targetElement, "mousemove", 0);

((JavascriptExecutor) driver).executeScript(script, targetElement, "mouseup", 0);

As web applications become more complex, the need to master the drag-and-drop operation in Selenium increases. Knowing the subtleties of the implementation methods and adapting to different scenarios are ways to make automated scripts more robust and reliable. This information can help you prepare for selenium interview questions.

 

Conclusion

We have discussed many techniques, from basic drag-and-drop operations to advanced offset-based movements. These skills allow a tester to mimic complex user interaction with the application under test correctly. The more interactive web applications become, the more critical the skill will be in dragging and dropping operations. By knowing the multiple approaches and their applications, you can create more solid and versatile automation scripts.

 

Frequently Asked Questions

What is drag and drop in Selenium?

In Selenium, drag-and-drop is a method for automating the drag-and-drop feature of web elements to another location, as end users do.

How do you drag and drop a file using Selenium?

We can drag and drop a file using the sendKeys method available for the file input element. The sendKeys method will accept a full file path as an argument.

How do you drag and drop a frame in Selenium?

First, switch to the frame using a driver. switch ().frame(). Then, the drag-and-drop operation on elements within the frame is performed.

How can drag-and-drop operations be performed?

Use the Actions class in Selenium. Create an Actions object, then call dragAndDrop() or dragAndDropBy() methods to operate.

Upcoming Batches For Selenium Course
Course NameDateDetails
Selenium Course

Class Starts on 16th December,2024

16th December

MON-FRI (Weekday Batch)
View Details
Selenium Course

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Drag and Drop in Selenium?

edureka.co