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);
}
} 相关推荐
wusiye 2020-10-23
表格的现在还是较为常用的一种标签,但不是用来布局,常见处理、显示表格式数据。在HTML网页中,要想创建表格,就需要使用表格相关的标签。<table> <tr> <td>单元格内的文字</td> ...
gufudhn 2020-08-09
nercon 2020-08-01
swiftwwj 2020-07-21
nercon 2020-07-16
饮马天涯 2020-07-05
Lophole 2020-06-28
gufudhn 2020-06-12
csstpeixun 2020-06-11
huzijia 2020-06-09
WebVincent 2020-06-06
行吟阁 2020-05-30
qsdnet我想学编程 2020-05-26
gufudhn 2020-05-25
qsdnet我想学编程 2020-05-19
suixinsuoyu 2020-05-15
HSdiana 2020-05-15
PioneerFan 2020-05-15