How to download .docx file using Selenium webdrive

2019-02-12 18:00发布

问题:

Can anyone let me know how to download a word file using selenium(java)? My below code is not working.

FirefoxProfile prof = new FirefoxProfile();
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/word");

When I click on 'download link or icon' in the page, it prompts a popup to save the download file (see image below) and I need to click on OK button in the popup.

Please let me know how to do this using Firefox.

回答1:

You need to use ROBOT class for firing an ENTER Action event. In java if you want to fire any event you have to use Robot class for typing using programatically or firing events like ENTER and ESCAPE.

// Create object of Robot class
Robot object=new Robot();

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

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

and for information regarding this you can use this link



回答2:

Try this

import java.awt.Robot;

And use

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

This will press Enter Programatically.



回答3:

Got it working using the following setup:

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);

More info about Preference settings can be found here: http://toolsqa.com/selenium-webdriver/how-to-download-files-using-selenium/.