如何透過 Selenium2 傳送鍵盤快捷鍵 ALT SHIFT z(熱鍵)?


我們可以透過 Selenium webdriver 傳送鍵盤快捷鍵 ALT SHIFT z(熱鍵)。這可以透過 Keys 類完成。我們將使用 Keys.chord 方法並傳遞 Keys.ALT、Keys.SHIFTz 作為該方法的引數。

從 Keys.chord 方法中獲得的整個值都作為字串形式獲得。然後將它作為引數傳送到 sendKeys 方法。

語法

String s = Keys.chord(Keys.ALT, Keys.SHIFT,"z");
driver.findElement(By.tagName("html")).sendKeys(s);

示例

帶 Keys.chord 方法的程式碼實現。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class HtKeys{
   public static void main(String[] args) {
         System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://tutorialspoint.tw/index.htm");
      // sending ALT,SHIFT and z by the Keys.Chord
      String s = Keys.chord(Keys.ALT, Keys.SHIFT,"z");
      driver.findElement(By.tagName("html")).sendKeys(s);
      driver.quit();
   }
}

還可以藉助 Actions 類來完成此操作。我們必須建立 Actions 類的物件,並在該物件上應用 keyUpkeyDown 方法,並將 Keys.ALT、Keys.SHIFTz 傳遞給這些方法。

語法

Actions a = new Actions(driver);
a.keyDown(Keys.ALT).keyDown(Keys.SHIFT).
sendKeys("z").keyUp(Keys.ALT).keyUp(Keys.SHIFT).build().perform();

示例

帶 Actions 的程式碼實現。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class HotKeyAction{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/index.htm");
      // Actions class with keyUp and keyDown methods
      Actions a = new Actions(driver);
      a.keyDown(Keys.ALT).keyDown(Keys.SHIFT).
      sendKeys("z").keyUp(Keys.ALT).keyUp(Keys.SHIFT).build().perform();
      driver.quit();
   }
}

更新於: 02-2 月-2021

2K+ 瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.