Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save PDF instead of opening in Selenium

There was a code I use that would always download the PDF. Since recently it started to open the PDF inside the browser. The same happens for both chrome and firefox.

In chrome I already tried:

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--disable-extensions"));
driver = new ChromeDriver(capabilities);

And in firefox I tried:

FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser. download. manager. useWindow",true);
firefoxProfile.setPreference("plugin.disable_full_page_plugin_for_types", "application/pdf");
firefoxProfile.setPreference("browser.download.dir","C:\\Documents and Settings\\xxxx\\My Documents\\Downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/pdf;text/plain;text/csv");
firefoxProfile.setPreference("pdfjs.disabled", true);
firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force",false);
firefoxProfile.setPreference("plugin.scan.plid.all",false);
firefoxProfile.setPreference("plugin.scan.Acrobat","99.0");

But still, both browsers are opening the PDF instead of saving it.

Any ideas?

like image 834
user3905599 Avatar asked Aug 07 '15 06:08

user3905599


2 Answers

Basically change the options like below:

// this will make automatically download to the default folder.
chromeOptions.AddUserProfilePreference("plugins.always_open_pdf_externally", true);

C# Selenium Saving pdf page

like image 103
Haryono Avatar answered Oct 29 '22 03:10

Haryono


I can show you how we did it in Ruby, and hopefully you can translate it to fit your Java (?) code. The main thing is figuring out which preference keys to set.

Capybara.register_driver :selenium_chrome_downloads do |app|
  prefs = {
    plugins: {
      plugins_disabled: ['Chrome PDF Viewer']
    },
    download: {
      prompt_for_download: false,
      default_directory: 'desired/download/path'
    }
  }
  Capybara::Selenium::Driver.new(app, browser: :chrome, prefs: prefs)
end
Capybara::Session.new(:selenium_chrome_downloads)

This maps to preference strings like "plugins.plugins_disabled", "download.prompt_for_download", and "download.default_directory"

Helpful docs: https://sites.google.com/a/chromium.org/chromedriver/capabilities (mostly Java) https://code.google.com/p/selenium/wiki/RubyBindings (for Ruby)

like image 40
nruth Avatar answered Oct 29 '22 04:10

nruth