1. 程式人生 > 實用技巧 >5.selenium之模擬滑鼠操作

5.selenium之模擬滑鼠操作

現在的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();