通過前面例子了解到,可以使用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中存儲的行為, 可以理解成是對整個操作的提交動作。
1.關於鼠標操作的其它方法
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();