前言
ActionChains和TouchAction可以用来模拟点击、双击、滑动等事件。
- ActionChains用于执行PC端的鼠标移动、按键、拖拽等事件;
- TouchActions用法与ActionChains类似,可以用来模拟移动端的点击、滑动、拖拽等手势操作;
- 最后需要调用 perform() 方法执行所有的操作;
一、ActionChains 编写方式
- 链式
ActionChains(driver).move_to_element(element).click(element).perform();
- 分步式
Action action = new Acthon(driver);
action.move_to_element(element);
action.click();
action.perform();
二、使用示例
1.通过 ActionChains 实现鼠标移动,单击,双击,右键等操作;
代码如下(示例):
driver.get("http://sahitest.com/demo/clicks.htm");
// 单击
actions.moveToElement(driver.findElement(By.xpath("//input[@value='click me']"))).click().perform();
// 双击
actions.moveToElement(driver.findElement(By.xpath("//input[@value='dbl click me']"))).doubleClick().perform();
// 右键
actions.moveToElement(driver.findElement(By.xpath("//input[@value='right click me']"))).contextClick().perform();
2.元素拖动
代码如下(示例):
driver.get("https://sahitest.com/demo/dragDropMooTools.htm");
WebElement drag = driver.findElement(By.id("dragger"));
WebElement drop = driver.findElement(By.xpath("//div[@class='item'][last()]"));
// 写法 1
// actions.dragAndDrop(drag, drop).perform();
// 写法 2
actions.clickAndHold(drag).moveToElement(drop).release().perform();