如何使用 Selenium 按下键盘按键?
我们可以使用 Selenium webdriver 按住一个键。我们大多利用 CONTROL/SHIFT/ALT 键按住,然后点击其他按键。因此,仅引用诸如 keys.CONTROL/ keys.SHIFT 或 Keys.ALT 之类的修饰符键是不够的。
为了在按下另一个键的同时按住一个键,我们使用 keyDown() 和 keyUp() 方法。这两个方法都接受修饰符键作为参数。
这两个方法对键的操作会产生键的特殊功能。所有这些方法都是 Selenium 中 Actions 类的部分。我们必须将导入 org.openqa.selenium.interactions.Actions 包添加到我们的代码中,以便使用 Actions 类下的方法。
示例
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
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.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class MetdKeyDown{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// identify element
WebElement l = driver.findElement(By.id("gsc-i-id1"));
// Actions class
Actions a = new Actions(driver);
// moveToElement() and then click()
a.moveToElement(l).click();
//enter text with keyDown() SHIFT key ,keyUp() then build() ,perform()
a.keyDown(Keys.SHIFT);
a.sendKeys("hello").keyUp(Keys.SHIFT).build().perform();
driver.quit()
}
}输出

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP