(八)模拟鼠标操作

虫师 创建于 almost 7 years 之前

最后更新: 2 months 之前

阅读数: 1

(八)模拟鼠标操作


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

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

  • contextClick() 右击

  • clickAndHold() 鼠标点击并控制

  • doubleClick() 双击

  • dragAndDrop() 拖动

  • release() 释放鼠标

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

百度首页设置悬停下拉菜单。

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中存储的行为, 可以理解成是对整个操作的提交动作。


关于鼠标操的其它方法


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();
0

相关课程

测试工具合集
图文
测试工具合集

课程分类: 自动化测试 测试工具 中间件

我们收集的各种测试工具

  • 已完结
  • 已更新7集
  • 最后更新时间: 2024-03-18 12:04:41

免费

查看详情
selenium python 综合教程
图文
selenium python 综合教程

课程分类: 自动化测试

selenium python入门及提升

  • 已完结
  • 已更新21集
  • 最后更新时间: 2024-03-18 10:51:39

免费

查看详情
selenium javascript教程
图文
selenium javascript教程

课程分类: 自动化测试

通过selenium来入门js

  • 已完结
  • 已更新21集
  • 最后更新时间: 2024-03-18 10:29:34

免费

查看详情