我尝试使用Selenium WebDriver和Robot类在IE11中下载文件,我使用IntelliJ并在带有IE11的Selenium Grid上运行测试。
我不使用element.click()函数,因为控件停在那里,因此我使用sendKeys来专注于donwload按钮。出现下载弹出窗口,这里是Robot类。我尝试在机器人的帮助下按Alt+S
保存文件,但它没有在IE上按Alt+S
,而是在我的IntelliJ上按Alt+S
而不是!!!这是我的代码:
if (webBrowser.equalsIgnoreCase("ie")) {
WebElement downloadReport = webDriver.findElement(By.id("clientReportDownload"));
try {
Robot robot = new Robot();
// sendKeys to focus on Download button and press Enter to download
downloadReport.sendKeys("");
downloadReport.sendKeys(Keys.ENTER);
waitSeconds(2);
// wait for Download popup
robot.setAutoDelay(250);
// simulate presse Alt + S to save file -> It presses Alt+S on IntelliJ instead !!!
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
waitSeconds(2);
} catch (AWTException e) {
e.printStackTrace();
}
}
有人有解决方案吗?
答案 0 :(得分:0)
您应首先使用点击。你可以尝试一下,它对我来说很好吗
driver.findElement(By.id("element_id")).click();
Robot robot = new Robot(); // Robot class throws AWT Exception
Thread.sleep(2000); // Thread.sleep throws InterruptedException
robot.keyPress(KeyEvent.VK_DOWN); // press arrow down key of keyboard to navigate and select Save radio button
Thread.sleep(2000); // sleep has only been used to showcase each event separately
robot.keyPress(KeyEvent.VK_TAB);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_TAB);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_TAB);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
答案 1 :(得分:0)
所以,我意识到,点击“下载”按钮后,Web浏览器的焦点会以某种方式丢失,因此我需要在Robo命令启动之前将焦点设置回Web浏览器,例如:
(JavascriptExecutor)webDriver.executeScript("window.focus();");
然后模拟按键作品!
答案 2 :(得分:0)
Robot robot;
try {
// pressing download button
dr.findElement(By.xpath("//a[@class='btn btn-primary']")).sendKeys("""");
robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
// handling download
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_S);
Thread.sleep(2000);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_TAB);
System.out.println("tab entered ");
System.out.println("Download completed");
} catch (Exception e) {
e.printStackTrace();
}