使用selenium时如何处理Windows文件上传窗口

我正在尝试使用java为网站编写selenium测试。 但是,我在测试文件上传时遇到了一个问题。

当我单击文件上传按钮时,它会自动打开Windows文件上传。 我有代码工作将文本成功地放在上传框中,只是我没有办法阻止Windows框自动启动,并且让网站不自动打开Windows文件上传并不是一个真正的选择。 通过研究这个主题,我知道selenium webdriver无法处理这个问题。 所以我的问题是:我可以通过自动方式关闭上传窗口的方式是什么?

我已经尝试过java机器人类,但它没有用。 它等到上传窗口关闭之后再执行我给它的任何命令(ALT-F4,点击xy位置等)

提前致谢

编辑:

wait.until(ExpectedConditions.elementToBeClickable(By.id(("addResourcesButton")))); driver.findElement(By.id("addResourcesButton")).click(); //popup window comes up automatically at this point try { Robot robot = new Robot(); robot.mouseMove(875, 625); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK); } catch (AWTException e) { e.printStackTrace(); } //my attempt to move the mouse and click, doesn't move or click until after I close the windows upload box String fileToUpload = "C:\\file.png"; WebElement uploadElement = driver.findElement(By.id("fileInput")); uploadElement.sendKeys(fileToUpload); //Takes the code and successfully submits it to the text area, where I can now upload it 

您可以使用以下任一方法执行非阻止点击:

高级用户交互API ( JavaDocs )

 WebElement element = driver.findElement(By.whatever("anything")); new Actions(driver).click(element).perform(); 

或JavaScript:

 JavascriptExecutor js = (JavascriptExecutor)driver; WebElement element = driver.findElement(By.whatever("anything")); js.executeScript("arguments[0].click()", element); 

我已经回答了类似的问题。 上传提供了其他解决方案 – 比如使用AutoIT。 但我个人会推迟与任何特定于操作系统的对话进行交互。 与特定于操作系统的对话交互将限制您从给定环境运行测试。

Selenium webdriver java – 使用phantomjs驱动程序上传文件

在上传时,始终识别“文件”类型的元素并与之交互。 这将解决您的弹出窗口问题。

例如:在我的应用程序中,上传相关元素具有以下DOM –

    

在这种情况下,您可以将sendKeys方法用于“multiFileInput”,其类型为“file”。 这样它适用于所有FF,Chrome和无头浏览器。