top button

Is there a way to do drag and drop in Selenium WebDriver?

0 votes
12 views
posted Apr 26 by Arun

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

Use actions library for performing basic mouse and keyboard actions.

import org.openqa.selenium.interactions.Actions;
    new Actions(driver).dragAndDrop(source, target).build().perform();

If your application is not responding - then it indicates your application cannot withstand the speed of selenium interaction classes.
Use the robot classes to achieve the same using sleeps.

Point fromLocation = source.getLocation();
        Point toLocation = target.getLocation();

        Robot robot = new Robot();

        Dimension fromSize = source.getSize();
        Dimension toSize = target.getSize();
        // Make Mouse coordinate center of element
        toLocation.x += toSize.width / 2;
        toLocation.y += toSize.height / 2 + 120;
        fromLocation.x += fromSize.width / 2;
        fromLocation.y += fromSize.height / 2 + 120;

        // Move mouse to drag from location
        robot.mouseMove(fromLocation.x, fromLocation.y);
        // Click and drag
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);

        // Drag events require more than one movement to register
        // Just appearing at destination doesn't work so move halfway first
        robot.mouseMove(((toLocation.x - fromLocation.x) / 2) + fromLocation.x,
                ((toLocation.y - fromLocation.y) / 2) + fromLocation.y);

        robot.delay(3000);
        // Move to final position
        robot.mouseMove(toLocation.x, toLocation.y);
        robot.delay(3000);
        // Drop
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

Here source and target is the WebElements to you need to drag from and to resp.

answer Apr 26 by Harish B
...