Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

Set Firefox profile to download files automatically using Selenium and Java

I want to verify file download using Selenium WebDriver and Java. The file to download is of PDF format. When WebDriver clicks on "Download" link in the AUT, Firefox opens up the following download confirmation window:

Download Confirmation Window

I want Firefox to download the file automatically without showing above confirmation window, so I used the below code:

FirefoxProfile firefoxProfile=new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir",downloadPath);
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/pdf");
WebDriver driver=new FirefoxDriver(firefoxProfile); 

but still Firefox shows the same window. How can I set Firefox profile so that PDF files are downloaded automatically without showing the confirmation dialogue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just like @Jason suggested, it's most probably another mime type. To get the mime type:

  • Open Developer Tools
  • Go to Network
  • Click on the link to download the pdf
  • In the network panel, select the first request
  • The mime type is the Content-Type from the response header:

enter image description here

Then to download a PDF with Firefox:

FirefoxOptions options = new FirefoxOptions();
options.setPreference("browser.download.folderList", 2);
options.setPreference("browser.download.dir", "C:\Windows\temp");
options.setPreference("browser.download.useDownloadDir", true);
options.setPreference("browser.download.viewableInternally.enabledTypes", "");
options.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf;text/plain;application/text;text/xml;application/xml");
options.setPreference("pdfjs.disabled", true);  // disable the built-in PDF viewer

WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.mozilla.org/en-US/foundation/documents");
driver.findElement(By.linkText("IRS Form 872-C")).click();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...