如何告诉selenium在打印弹出窗口上按取消?

我正在检查是否使用selenium显示页面。 然而,当我单击该页面时,会出现打印机打印提示(如选择打印机等的窗口)。 如何通过点击取消关闭此窗口的selenium?

我试着查看警报,但似乎那些不起作用,因为打印窗口是系统提示。 它无法识别出现的任何警报。

我尝试使用的最新版本只是发送像tab一样的键并输入以便选择取消按钮,但它不会识别任何按键被按下。

我怎么处理这个案子?

public static boolean printButton() throws Exception { WebDriver driver = new FirefoxDriver(); // Keyboard keyboard = driver.getKeyboard(); driver.get("website"); try { Thread.sleep(3000); WebElement temp = driver.findElement(By.xpath("//*[@id='block-print-ui-print-links']/div/span/a")); temp.click(); Actions action = new Actions(driver); action.sendKeys(Keys.TAB).sendKeys(Keys.ENTER); Thread.sleep(6000); } catch (Exception e) { System.out.println("No button"); driver.close(); return false; } 

我只需通过覆盖print方法来禁用打印对话框:

 ((JavascriptExecutor)driver).executeScript("window.print=function(){};"); 

但如果您的目标是测试打印被调用,那么:

 // get the print button WebElement print_button = driver.findElement(By.cssSelector("...")); // click on the print button and wait for print to be called driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS); ((JavascriptExecutor)driver).executeAsyncScript( "var callback = arguments[1];" + "window.print = function(){callback();};" + "arguments[0].click();" , print_button); 

实际上你无法处理Selenium WebDriver中的窗口(OS)对话框。 这就是selenium团队在这里回答的问题

当前团队的立场是打印对话框超出了项目的范围。 WebDriver / Selenium专注于模拟用户与网页呈现内容的交互。 浏览器的其他方面包括但不限于打印对话框,保存对话框和浏览器镶边,都超出了范围。

你可以尝试像AutoIt这样的不同方法

如果您只想测试Chrome浏览器,那么这是我的解决方案。 由于’机器人’类或禁用打印不适用于我的情况。

 // Choosing the second window which is the print dialog. // Switching to opened window of print dialog. driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString()); // Runs javascript code for cancelling print operation. // This code only executes for Chrome browsers. JavascriptExecutor executor = (JavascriptExecutor) driver.getWebDriver(); executor.executeScript("document.getElementsByClassName('cancel')[0].click();"); // Switches to main window after print dialog operation. driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString()); 

基于原生窗口的对话框可以由AutoItX处理,如以下代码中所述

 File file = new File("lib", jacobDllVersionToUse); System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath()); WebDriver driver = new FirefoxDriver(); driver.get("http://www.joecolantonio.com/SeleniumTestPage.html"); WebElement printButton = driver.findElement(By.id("printButton")); printButton.click(); AutoItX x = new AutoItX(); x.winActivate("Print"); x.winWaitActive("Print"); x.controlClick("Print", "", "1058"); x.ControlSetText("Print", "", "1153", "50"); Thread.sleep(3000); //This was added just so you could see that the values did change. x.controlClick("Print", "", "2"); 

参考: http : //www.joecolantonio.com/2014/07/21/selenium-how-to-handle-windows-based-dialogs-and-pop-ups/