Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag and drop the image into the BOX- selenium with java

I want to perform drag and drop in W3school web page using selenium. Code is working fine but output is not showing on the webpage.

link is :- http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop

My code is :-

public String dragAndDrop(String object,String data){
    APP_LOGS.debug("waiting for popup closer");
    try{

        driver.switchTo().frame("iframeResult");
        WebElement element = driver.findElement(By.xpath(".//*[@id='drag1']"));
        WebElement target = driver.findElement(By.xpath(".//*[@id='div1']"));
        (new Actions(driver)).dragAndDrop(element, target).build().perform();
    }catch(Exception e){
        return Constants.KEYWORD_FAIL+" -- Unable to drag"+e.getMessage();

    }

    return Constants.KEYWORD_PASS;
}
like image 885
Shasak Singh Sengar Avatar asked Mar 24 '26 03:03

Shasak Singh Sengar


1 Answers

We can also interact with keyboard / mouse events using Actions class and robot class in Selenium. I have used Robot class to resolve your issue.

The Robot class is present in java.awt package. You can check all the methods in the docs.

public static void Task1() throws AWTError, AWTException, InterruptedException
{
    WebDriver driver = new FirefoxDriver();

    driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop");

    driver.switchTo().frame("iframeResult");
    WebElement element1 = driver.findElement(By.xpath(".//img[@id='drag1']"));
    WebElement element2 = driver.findElement(By.xpath(".//*[@id='div1']"));
    Actions action = new Actions(driver);

    Point element3 = driver.findElement(By.xpath(".//*[@id='drag1']")).getLocation();
    int i=element3.getX()+800;
    int b=element3.getY()+250;

    Robot robot = new Robot();
    robot.mouseMove(i, b);
    // Press left click of mouse
    robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
    robot.delay(4000);
    robot.mouseMove(i+20, b-120);

    robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);

    robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

    Thread.sleep(10000);
    driver.close();
}
like image 140
Ashish Kumar Singh Avatar answered Mar 25 '26 15:03

Ashish Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!