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