10

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.

Save Popup

justcurious
  • 839
  • 3
  • 12
  • 29
Deepak gupta
  • 291
  • 4
  • 5
  • 15

3 Answers3

10

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.

Vaibhav
  • 2,073
  • 4
  • 23
  • 26
7

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

Luffy
  • 1,317
  • 1
  • 19
  • 41
  • 1
    Will only work if run on a local machine, a robot class will not work when connecting to a remote browser (e.g. selenium gird, sauce labs, etc) because you are only controlling the cursor on the local machine. Generally this is a really bad and unreliable idea. – Ardesco Apr 26 '19 at 10:03
2

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/.

Alex
  • 357
  • 2
  • 15