问题
I'm trying to automatically download .pdf files in geckodriver/Firefox. I've searched on stackoverflow and other resources and think the code below should work:
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", 'C:\\Users\\xyz\\Downloads\\')
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream,application/pdf,application/x-pdf,application/vnd.pdf")
profile.set_preference("pref.downloads.disable_button.edit_actions", True)
profile.set_preference("browser.helperApps.neverAsk.openFile", "application/octet-stream,application/pdf,application/x-pdf,application/vnd.pdf")
browser = webdriver.Firefox(firefox_profile=profile)
I also tried:
profile.set_preference("pdfjs.disabled", True)
However, Firefox does not automatically download the .pdf (even though it is application/pdf in the http req). Also, after I load that profile in Firefox, under "Options / Applications", the PDF format still shows "Preview in Firefox" instead of "Save File"... What am I doing wrong?
回答1:
Try by adding the following preference also, to the existing list:
fp.setPreference("pdfjs.enabledCache.state", false);
fp.setPreference("browser.helperApps.neverAsk.openFile","application/pdf");
回答2:
To disable open and download pdf in firefox:
FirefoxOptions options = new FirefoxOptions();
options.addPreference("browser.download.folderList", 2);
options.addPreference("browser.download.dir", pathToDownload);
options.addPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
options.addPreference("pdfjs.enabledCache.state",false);
WebDriver driver = new FirefoxDriver(options);
来源:https://stackoverflow.com/questions/51882416/geckodriver-selenium-auto-download-pdfs