3

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;
}

1 Answers1

1

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();
}
Lukas Körfer
  • 13,515
  • 7
  • 46
  • 62