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

本文介绍了一种使用 Java 和 Selenium WebDriver 实现网页元素拖拽的方法。通过获取元素的位置和尺寸,利用 AWT Robot 类模拟鼠标操作完成从源位置到目标位置的拖拽过程。该方法无需直接操作 DOM 元素,适用于需要精确控制鼠标移动的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

优点:无需获得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);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值