如何使用 Selenium 按住某个键?
seleniumautomation testingtesting tools
我们可以使用 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://www.tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// 识别元素
WebElement l = driver.findElement(By.id("gsc-i-id1"));
// 动作类
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()
}
}
输出


