Selenium提供了一个强大的用于真实的模拟用户交互的一个类----Actions,这个类提共了一系列的API供模拟交互:
keyDown : 用于模拟按键被按下
keyUp : 用于模拟按键松开
doubleClick : 用于模拟双击
clickAndHold : 用于模拟鼠标左键点住不放开
release : 用于模拟松开鼠标,与clickAndHold相配合
moveToElement : 将鼠标移动至元素的中间位置
contextClick : 模拟鼠标右键点击
dragAndDrop : 拖拽
这里由于测试页面的限制我就只举一个contextClick的例子:
package org.coderinfo.demo; 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 ActionDemo { private static final String URL = "http://www.baidu.com"; /** * @author Coderinfo * @E-mail coderinfo@163.com */ public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); //最大化浏览器界面 driver.get(URL); //访问度娘首页。 Thread.sleep(2000); //等待页面加载 WebElement input = driver.findElement(By.id("kw")); //获取百度搜索框 Actions ac = new Actions(driver); // 为driver 加载 actions ac.contextClick(input).perform(); // 在百度搜索框上点击右键 Thread.sleep(10000); driver.quit(); } } |