如何在selenium中输入shift + ctrl + s? 我用过
Actions action = new Actions(driver);
action.sendKeys(Keys.chord(Keys.SHIFT + Keys.CONTROL + "s")).perform();
其投掷错误
答案 0 :(得分:1)
如果你只是发送一系列密钥,那么每个密码的Webdriver首先按一个给定的密钥,然后按下它。
因此,您的代码sendKeys(Keys.chord(Keys.SHIFT + Keys.CONTROL + "s")
等同于当时的以下系列事件:
这不是您想要的,因为您在按下S键的时刻想到按下了Ctrl和Shift并且被保持。
您需要使用Actions#keyDown方法按键并将其保持在按下状态,稍后Actions#keyUp以释放密钥。所以行动的顺序可能是:
keyDown
keyDown
sendKeys
方法按下此键并立即释放)keyUp
keyUp
必须完成第5点和第6点(释放键),以避免在测试代码中出现意外影响(不要将Ctrl + Shift置于按下状态)。
以下是simple page on jsfiddle的链接,可帮助我们测试我们的WebDriver代码。
<body>
<p>Press a key on the keyboard in the input field to find out if the Ctrl-SHIFT key was pressed or not.</p>
<input id="ctrl_shift_s" type="text" onkeydown="isKeyPressed(event)">
<p id="demo"></p>
<script>
function isKeyPressed(event) {
console.log( event.keyCode);
var x = document.getElementById("demo");
if (event.shiftKey && event.ctrlKey && event.keyCode == 83 ) {
x.innerHTML = "The Ctrl-SHIFT-S keys were pressed!";
} else {
x.innerHTML = "Please press Ctrl-SHIFT-S";
}
}
</script>
</body>
如果将光标移动到此页面上的INPUT字段(此元素的id =“ctrl_shift_s”),然后按Ctrl-SHIFT-S键(按住SHIFT和Ctrl键),则会出现一条消息按下了Ctrl-SHIFT-S键!
以下是使用最新的IE,Firefox和Chrome驱动程序对上述测试页面进行测试的示例(工作)代码。您必须使用requireWindowFocus();
选项才能在IE驱动程序中运行Actions
。
WebDriver driver= null;
try{
System.setProperty("webdriver.ie.driver", "C:\\instalki\\IEDriverServer.exe");
System.setProperty("webdriver.chrome.driver", "C:\\instalki\\chromedriver.exe");
System.setProperty("webdriver.gecko.driver", "C:\\instalki\\geckodriver.exe");
InternetExplorerOptions opt = new InternetExplorerOptions();
opt.requireWindowFocus();
// driver=new InternetExplorerDriver(opt);
// driver = new ChromeDriver();
driver = new FirefoxDriver();
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait( driver, 10);
driver.get("https://jsfiddle.net/39850x27/2/");
final By inputField = By.id("ctrl_shift_s");
final By messageWeWaitFor = By.xpath("//*[text() = 'The Ctrl-SHIFT-S keys were pressed!' ]");
final By frame = By.name("result");
// Swift to a frame (our test page is within this frame)
driver.switchTo().frame(driver.findElement(frame));
// move a corsor to the field
wait.until(ExpectedConditions.elementToBeClickable(inputField)).click();
Actions a = new Actions(driver);
// Press SHIFT-CTRL-S
a.keyDown(Keys.SHIFT)
.keyDown(Keys.CONTROL)
.sendKeys("s")
.build()
.perform();
//Wait for a message
wait.until(ExpectedConditions.visibilityOfElementLocated(messageWeWaitFor));
System.err.println("Success - Ctrl-Shift-S were pressed !!!");
// Sleep some time (to see the message is really on the page)
Thread.sleep(5000);
// Release SHIFT+CTRL keys
a.keyUp(Keys.CONTROL)
.keyUp(Keys.SHIFT)
.build()
.perform();
}finally {
if(driver!=null) {
driver.quit();
}
}