如何使用Java中的Selenium Webdriver下载.docx文件?

10

有人能告诉我如何使用selenium(java)下载Word文件吗?我的下面的代码不起作用。

FirefoxProfile prof = new FirefoxProfile();
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/word");
当我在页面上点击“下载链接或图标”时,会弹出一个提示框来保存下载文件(见下图),我需要在提示框中点击“OK”按钮。请告诉我如何在Firefox中完成这个操作。 Save Popup
3个回答

10

试试这个

import java.awt.Robot;

使用

Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

这将以编程方式按下Enter键。


7
您需要使用ROBOT类来触发ENTER操作事件。在Java中,如果您想要触发任何事件,您必须使用Robot类进行编程输入或触发诸如ENTER和ESCAPE之类的事件。
// Create object of Robot class
Robot object=new Robot();

// Press Enter
object.keyPress(KeyEvent.VK_ENTER);

// Release Enter
object.keyRelease(KeyEvent.VK_ENTER);

关于此事的相关信息,请使用链接


1
只有在本地机器上运行时才能正常工作,当连接到远程浏览器(例如selenium gird、sauce labs等)时,机器人类将无法工作,因为您只能控制本地机器上的光标。通常这是一个非常糟糕和不可靠的想法。 - Ardesco

2

使用以下设置使其正常工作:

FirefoxOptions options = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", "C:\\Windows\\temp");
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
options.setProfile(profile);
driver = new FirefoxDriver(options);

更多有关偏好设置的信息可以在这里找到:http://toolsqa.com/selenium-webdriver/how-to-download-files-using-selenium/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接