Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - how to change the default directory for the downloaded file using chrome browser

I tried to use below but still the pdf file goes to the old default directory.

String downloadFilepath = "/target";    
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("download.default_directory", downloadFilepath);        
options.setExperimentalOption("prefs", chromePrefs);
driver = new ChromeDriver(options);
question from:https://stackoverflow.com/questions/65845989/how-to-change-the-default-directory-for-the-downloaded-file-using-chrome-browser

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

1 Answer

0 votes
by (71.8m points)

The main problem with your code is that you haven't provided the proper download path.

String downloadFilepath = "/target"; 

Replace or Change it with below code:

String downloadFilepath = System.getProperty("user.dir") + File.separator + "target";

Complete Code for testing:

String downloadFilepath = System.getProperty("user.dir") + File.separator + "target";   
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromePrefs = new HashMap<>();
chromePrefs.put("download.default_directory", downloadFilepath);    
chromePrefs.put("download.prompt_for_download", false);
chromePrefs.put("download.directory_upgrade",true);
options.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(options);
//Example Site for REF
driver.get("http://the-internet.herokuapp.com/download/some-file.txt");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...