目录

(八)模拟鼠标操作

目录

通过前面例子了解到,可以使用click()来模拟鼠标的单击操作,现在的Web产品中提供了更丰富的鼠标交互方式, 例如鼠标右击、双击、悬停、甚至是鼠标拖动等功能。在WebDriver中,将这些关于鼠标操作的方法封装在ActionChains类提供。

Actions 类提供了鼠标操作的常用方法:

  • contextClick() 右击

  • clickAndHold() 鼠标点击并控制

  • doubleClick() 双击

  • dragAndDrop() 拖动

  • release() 释放鼠标

  • perform() 执行所有Actions中存储的行为

百度首页设置悬停下拉菜单。 http://orru5lls3.bkt.clouddn.com/xuanting.jpg

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class MouseDemo {

  public static void main(String[] args) {

    WebDriver driver = new ChromeDriver();
    driver.get("https://www.baidu.com/");

    WebElement search_setting = driver.findElement(By.linkText("设置"));
    Actions action = new Actions(driver);
    action.clickAndHold(search_setting).perform();

    driver.quit();
  }
}
  • import org.openqa.selenium.interactions.Actions;

导入提供鼠标操作的 ActionChains 类

  • Actions(driver) 调用Actions()类,将浏览器驱动driver作为参数传入。

  • clickAndHold() 方法用于模拟鼠标悬停操作, 在调用时需要指定元素定位。

  • perform() 执行所有ActionChains中存储的行为, 可以理解成是对整个操作的提交动作。


### 关于鼠标操的其它方法 ```java

import org.openqa.selenium.interactions.Actions; ……

Actions action = new Actions(driver);

// 鼠标右键点击指定的元素 action.contextClick(driver.findElement(By.id(“element”))).perform();

// 鼠标右键点击指定的元素 action.doubleClick(driver.findElement(By.id(“element”))).perform();

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

// 释放鼠标 action.release().perform();





原始封面

![课程图片](https://images.unsplash.com/photo-1455894127589-22f75500213a?w=300)