现在的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.interactions.Actions; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class MouseDemo { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); WebElement search_setting = driver.findElement(By.id("s-usersetting-top")); Actions actions = new Actions(driver); actions.clickAndHold(search_setting).perform(); Thread.sleep(5000); driver.findElement(By.linkText("高级搜索")).click(); Thread.sleep(2000); driver.findElement(By.name("q1")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//*[@id="wrapper"]/div[6]/span/i")); Thread.sleep(2000); 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();