pythonbashgoogle-chromeselenium-webdriverselenium-chromedriver

Set the download directory in Google Chrome via a .bat file or selenium


I need to set a unique download directory for a specific profile in Google Chrome, not manually, but through the command line or in another way. ChromeOptions I used:

options.add_argument('--allow-profiles-outside-user-dir')
options.add_argument('--enable-profile-shortcut-manager')
options.add_argument(rf'user-data-dir=C:\User')
options.add_argument('--profile-directory=Profile 1')
options.add_argument('ignore-certificate-errors')

I tried to write the script myself, but nothing worked. I didn’t find the required line with the download directory in the chrome preferences file. Maybe I was looking in the wrong place.
Also I tried options.add_argument(f"download.default_directory={download_path}") but that didn't work either.

Example script:

@echo off
"C:\Program Files\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\Path\To\Your\Custom\Profile" --download.default_directory="C:\Path\To\Your\Download\Directory"

Solution

  • Use add_experimental_option() with "prefs" to set the download directory.

    This combination of preferences worked for me: (Set DOWNLOAD_PATH first.)

    from selenium import webdriver
    
    prefs = {
        "download.default_directory": DOWNLOAD_PATH,
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "default_content_setting_values.notifications": 0,
        "default_content_settings.popups": 0,
        "managed_default_content_settings.popups": 0,
        "profile.default_content_setting_values.notifications": 2,
        "profile.default_content_settings.popups": 0,
        "content_settings.exceptions.automatic_downloads.*.setting": 1,
        "profile.managed_default_content_settings.popups": 0,
        "profile.default_content_setting_values.automatic_downloads": 1,
    }
    options = webdriver.ChromeOptions()
    options.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(options=options)