Drag and Drop Operation in Selenium

By | 01/10/2015

You can perform Drag and Drop operation in Selenium by its provided Actions APIs. At that link, there are two simple html div elemennts and can drag one to on other element(with jQuery). You can do that with Selenium. To check it is done, there is a text in dropped place. Before drop text is :”Drop here“. After drop, text is: “Dropped!“. you can find both Python and Java code for that:

Python:

# -*- coding: UTF-8 -*-
from selenium import webdriver
from selenium.webdriver import ActionChains

driver = webdriver.Firefox()
driver.implicitly_wait(30)
driver.set_page_load_timeout(30)
driver.maximize_window()

driver.get("http://mahsumakbas.net/selenium/dragdrop.html")

drag_element = driver.find_element_by_id("draggable")
target_element = driver.find_element_by_id("droppable")

print "text before : " + target_element.text

action_chains = ActionChains(driver)
action_chains.drag_and_drop(drag_element, target_element).perform()

print "text after : " + target_element.text

driver.quit()

 

Java:

import java.io.IOException;

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.Action;
import org.openqa.selenium.interactions.Actions;

public class DragDrop {
    static WebDriver driver = new FirefoxDriver();

    public static void main(String[] args) throws IOException {

        driver.get("http://mahsumakbas.net/selenium/dragdrop.html");

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

        System.out.println("Text before Drag operation:"
                + targetElement.getText());
        Actions builder = new Actions(driver);

        Action dragAndDrop = builder.clickAndHold(dragElement)
                .moveToElement(targetElement).release(targetElement).build();

        dragAndDrop.perform();

        System.out.println("Text before Drag operation:"
                + targetElement.getText());

        driver.quit();
    }
}

 

P.S.: Thanks to Gürkan İlleez for his help to create html page with Drag&Drop feature.

Leave a Reply

Your email address will not be published. Required fields are marked *

*