Advanced User Interactions | Performing drag and drop operations

Quick Reference to perform drag-drop

//Drag and drop by pixels
builder.dragAndDropBy(element, xOffset, yOffset)
 .build()
 .perform();

//Drag one element over another element:
builder.dragAndDrop(sourceElement, targetElement).build().perform();
# Drag and drop by pixels
action_chains.drag_and_drop_by_offset(element, xOffset, yOffset).perform()

#Drag one element over another element
builder.drag_and_drop(sourceElement, targetElement).perform()

In the Previous Tutorial, we covered the following –

  • Introduction to Actions class
  • Action interface
  • Using moveToElement() method to move the mouse over an element
  • Methods build() and perform()

In this tutorial, we’ll learn to perform mouse drag-drop operations.

  • Use dragAndDropBy() method to drag a slider from left to right by some offsets
  • Use the same method as above but move the slider reverse. i.e. left to right or bottom to top
  • Drag an element over another element by using dragAndDrop() method

 Automate a sample drag-drop scenario

  • Navigate to the target URL – https://www.flipkart.com/search?q=laptop
  • Find the price filter element
  • Drag the price filter to some value
  • Drag the element (image) over another element (input box)

Write initial code

System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.flipkart.com/search?q=laptop");

//Find the slider element for the minimum price (left-most one)
WebElement leftSlider = driver.findElement(By.className("_3aQU3C"));

//Instantiate Actions
Actions builder = new Actions(driver);
# Navigate to the target page’s URL
driver_path = "C:/teachmeselenium/chromedriver.exe"
driver = webdriver.Chrome(driver_path )
driver.get("https://www.flipkart.com/search?q=laptop")

# Find the slider element for the minimum price (left-most one) 
leftSlider = driver.find_element_by_class_name("_3aQU3C")

# Instantiate ActionChains
action_chains = ActionChains(driver)

Drag the slider to its right by some offset (30 pixels)

builder.dragAndDropBy(leftSlider, 30, 0)
	.build()
	.perform();
action_chains.drag_and_drop_by_offset(leftSlider, 30, 0).perform()

Since we are moving the element left to right, with zero vertical movements we passed the second parameter as 0.

Drag the slider from right to left

// Find the slider element for the maximum price (right-most one)
WebElement rightSlider = driver.findElement(By.className("_3aQU3C"));

// Drag the slider to its left by some offset (20 pixels)
builder.dragAndDropBy(rightSlider, -20, 0)
	.build()
	.perform();
# Find the slider element for the maximum price (right-most one)
rightSlider = driver.find_element_by_class_name("_3aQU3C")

# Drag the slider to its left by some offset (20 pixels)
action_chains.drag_and_drop_by_offset(rightSlider, -20, 0).perform()

Why the heck you are passing a negative value -20?

Because we want the slider to be dragged right to left, instead of left to right. The negative value for x/y offset instructs the driver to drag reverse (right to left, bottom to top).

What are the parameters you are passing into that method?

public Actions dragAndDropBy(WebElement source,
                             int xOffset,
                             int yOffset)

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.

Returns: A self-reference.

drag_and_drop_by_offset(self, source, xoffset, yoffset):
        """
        Holds down the left mouse button on the source element,
           then moves to the target offset and releases the mouse button.

        :Args:
         - source: The element to mouse down.
         - xoffset: X offset to move to.
         - yoffset: Y offset to move to.
        """

Drag an element over another element

// Find the Logo element (source to drag) and Search box element (target over which we want to drag source) 
WebElement source = driver.findElement(By.xpath("//img[@alt='Flipkart']"));
WebElement target = driver.findElement(By.className("LM6RPg"));

builder.dragAndDrop(source, target).build().perform();

Here is the method definition of dragAndDrop:

public Actions 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.

Returns: A self reference.

# Find the Logo element (source to drag) and Search box element (target over which we want to drag source) 
source = driver.find_element_by_xpath("//img[@alt='Flipkart']")
target = driver.find_element_by_class_name("LM6RPg")

# Drag logo over search box 
action_chains.drag_and_drop(source, target).perform()

Method definition of drag_and_drop

def drag_and_drop(self, source, target):
        """
        Holds down the left mouse button on the source element,
           then moves to the target element and releases the mouse button.

        :Args:
         - source: The element to mouse down.
         - target: The element to mouse up.
        """

Complete Code

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 AdvancedUserInteraction_DragAndDrop {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver.exe");
		WebDriver driver = new ChromeDriver();
		driver.manage().window().maximize();
		driver.get("https://www.flipkart.com/search?q=laptop");
		//Find the slider element for minimum price (left-most one)
		WebElement leftSlider = driver.findElement(By.xpath("//div[@data-reactid='108']"));
		//Instantiate Actions
		Actions builder = new Actions(driver);
		//Drag the slider to its right by some offset (30 pixels)
		builder.dragAndDropBy(leftSlider, 60, 0)
				.build()
				.perform();
		//Wait for 5 seconds
		Thread.sleep(5000);
		//Find the slider element for maximum price (right-most one)
		WebElement rightSlider = driver.findElement(By.xpath("//div[@data-reactid='110']"));
		//Drag the slider to its left by some offset (20 pixels)
		builder.dragAndDropBy(rightSlider, -30, 0)
				.build()
				.perform();
		//Wait for 5 seconds
		Thread.sleep(5000);
		//Find the Logo element (source to drag) and Search box element (target over which we want to drag source) 
		WebElement source = driver.findElement(By.xpath("//img[@alt='Flipkart']"));
		WebElement target = driver.findElement(By.className("LM6RPg"));
		//Drag logo over search box
		builder.dragAndDrop(source, target).build().perform();
		//Quit driver
		driver.quit();
	}

}
from selenium import webdriver
from selenium.webdriver import ActionChains
import time

driver_path = webdriver.Chrome("C:\Shadab\lib\chromedriver.exe")
driver = webdriver.Chrome(driver_path )
driver.get("https://www.flipkart.com/search?q=laptop");

leftSlider = driver.find_element_by_class_name("_3aQU3C")
action_chains = ActionChains(driver)
action_chains.drag_and_drop_by_offset(leftSlider, 30, 0).perform()
time.sleep(5)

rightSlider = driver.find_element_by_class_name("_3aQU3C")
action_chains.drag_and_drop_by_offset(rightSlider, -20, 0).perform()
time.sleep(5)

source = driver.find_element_by_xpath("//img[@alt='Flipkart']")
target = driver.find_element_by_class_name("LM6RPg")
action_chains.drag_and_drop(source, target).perform()
driver.quit()

In the Next Tutorial, we will explore some of the methods to automate keyboard press events.

Leave a Reply