Java 模拟鼠标操作实现 Html5 Drag And Drop

优点:无需获得Element,只需要两个坐标就可以进行操作

缺点:独占性强,强制获得鼠标,运行过程中无法进行其他操作,坐标是屏幕坐标,计算坐标需要减去浏览器工具栏和地址栏的高度

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.*;
public class DragAndDrop {
    static WebDriver driver;
    public static void main(String[] args) throws Exception {
     System.setProperty("webdriver.chrome.driver", "F:\\workspace\\chromedriver_win32\\chromedriver.exe");
     driver = new ChromeDriver();
       
     // driver.get("http://www.w3schools.com/html/html5_draganddrop.asp");
     // driver.get("http://www.w3schools.com/html/tryhtml5_draganddrop.htm");
        driver.get("http://html5demos.com/drag");
        driver.manage().window().maximize();
        WebElement dragFrom = driver.findElement(By.xpath("//*[@id='one']"));
        WebElement dragTo = driver.findElement(By.xpath("//*[@id='bin']"));
        dragAndDropElement(dragFrom, dragTo);
    }
    public static void dragAndDropElement(WebElement dragFrom, WebElement dragTo) throws Exception {
     // Setup robot
        Robot robot = new Robot();
        robot.setAutoDelay(500);
        // Get size of elements
        Dimension fromSize = dragFrom.getSize();
        Dimension toSize = dragTo.getSize();
        Point toLocation = dragTo.getLocation();
        Point fromLocation = dragFrom.getLocation();
        //Make Mouse coordinate centre of element
        toLocation.x += toSize.width/2;
        toLocation.y += toSize.height/2 + 50 ;
        fromLocation.x += fromSize.width/2;
        fromLocation.y += fromSize.height/2 + 50;
 
        //Move mouse to drag from location
        robot.mouseMove(fromLocation.x, fromLocation.y);
        //Click and drag
        robot.mousePress(InputEvent.BUTTON1_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);
       
        //Move to final position
        robot.mouseMove(toLocation.x, toLocation.y);
        //Drop
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
    }
}

相关推荐