I am automating a reporting task using Selenium and ChromeDrive, but by default, all files are being saved to the system's "Downloads" folder. I need to programmatically specify a custom directory for these downloads to keep my project files organized. I’ve heard about using ChromeOptions and experimental preferences like download.default_directory, but I am struggling with the exact syntax. How do I ensure the browser doesn't prompt for a "Save As" location and instead forces the download into my defined local path?
3 answers
To control the download location, you must use the ChromeOptions class to pass experimental preferences to the browser before the driver initializes. You create an instance of options and use the .add_experimental_option method to set a dictionary of parameters. Specifically, you need to set download.default_directory to your absolute local path and download.prompt_for_download to False. It is also a good idea to set directory_upgrade to True and safebrowsing.enabled to True. This prevents the "This file may harm your computer" warning from blocking your automation. Once these options are defined, you pass them into the webdriver.Chrome constructor using the options parameter.
That configuration works perfectly for standard PDF or CSV files, but I've noticed that sometimes Chrome still opens a preview window instead of downloading the file. Is there a specific MIME type setting I need to add to these experimental preferences to force the browser to treat every file as a download rather than opening it in a new tab?
Make sure you are using absolute paths for your download directory. Selenium can be very finicky with relative paths, often defaulting back to the standard user downloads folder if it can't resolve the location.
I agree with Barbara. I personally use the os.path.abspath() function in Python to ensure the string passed to the Chrome preferences is always a full, valid system path. This saved me a lot of headaches when running my scripts across different environments like Windows and Linux
David, you can actually disable the built-in PDF viewer by adding "plugins.always_open_pdf_externally": True to your preferences dictionary. This forces Chrome to hand the file off to the download manager immediately rather than attempting to render it in the browser. It's a lifesaver for scrapers that need to collect invoices or technical manuals without manual intervention.