selenium 3.0鼠标事件 (java代码)

注意:ActionChains下相关方法在当前的firefox不工作,建议使用谷歌浏览器。

public static void main(String[] args) throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");

ChromeOptions Options = new ChromeOptions();
Options.addArguments("user-data-dir=C:\Users\happy\AppData\Local\Google\Chrome\User Data");
WebDriver driver = new ChromeDriver(Options);
driver.get("https://www.baidu.com");
Actions action = new Actions(driver);

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// 等待页面加载元素
try {


WebElement target = driver.findElement(By.xpath(".//*[@id='u1']/a[8]"));
// 定位百度首页中的【设置】按钮,此处建议用xpath
// 定位,如果用linkText可能会出现定位不到的情况。程序不报错,页面也没有任何显示。

action.moveToElement(target).perform();
// 鼠标悬停
action.clickAndHold(driver.findElement(By.xpath(".//*[@id='u1']/a[8]"))).perform();
// 鼠标悬停
Thread.sleep(10000);
// 线程等待是为了让初学者看到页面操作结果,实际工作中不建议用线程等待。
action.contextClick(driver.findElement(By.id("kw"))).perform();
// 鼠标右键操作

WebElement source = driver.findElement(By.name("element"));
WebElement target1 = driver.findElement(By.name("element"));
action.dragAndDrop(source, target1).perform();
// 鼠标拖拽动作,将source 元素拖放到target 元素的位置。

action.doubleClick(driver.findElement(By.name("element"))).perform();
// 双击鼠标
action.release().perform();
// 释放鼠标

} finally {
Thread.sleep(10000);
driver.close();
driver.quit();
}

原文地址:https://www.cnblogs.com/linxinmeng/p/6928683.html