Wen
Wen

Reputation: 103

Selenium Chrome: Load profile and change download folder - Python

OS: Win 10
Chrome: 81.0.4044.129
ChromeDriver: 81.0.4044.69

Goal:
Load an existing profile with extensions and preference configured AND specify default download locations.

Purpose:
I want to save images into their respective folders name.

Challenges
If I specify a Chrome profile to be loaded, then I cannot change the default download folder.


Code Snippets:

# Loading profile works!
options = webdriver.ChromeOptions()
options.add_argument(f'user-data-dir={profile_path}')
options.add_argument(f'--profile-directory={profile_name}')
driver = webdriver.Chrome(chrome_options=options)
# Changing default download location works!
options = webdriver.ChromeOptions()
prefs = {"download.default_directory" : "C:/Downloads/Folder A"}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=options)
# This DOESN'T work! Default download location is not changed. 
options = webdriver.ChromeOptions()
options.add_argument(f'user-data-dir={profile_path}')
options.add_argument(f'--profile-directory={profile_name}')
prefs = {"download.default_directory" : "C:/Downloads/Folder A"}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=options)


Is it possible to BOTH load the profile and change the default download location before the driver is created?


Upvotes: 2

Views: 2361

Answers (1)

Wen
Wen

Reputation: 103

I believe there isn't a way to both load an existing profile and also to change the default_directory option.
So instead, I used json.loads and json.dump to modify the 'Preference' file before loading the profile.

import json
from selenium import webdriver

# helper to edit 'Preferences' file inside Chrome profile directory.
def set_download_directory(profile_path, profile_name, download_path):
        prefs_path = os.path.join(profile_path, profile_name, 'Preferences')
        with open(prefs_path, 'r') as f:
            prefs_dict = json.loads(f.read())
        prefs_dict['download']['default_directory'] = download_path
        prefs_dict['savefile']['directory_upgrade'] = True
        prefs_dict['download']['directory_upgrade'] = True
        with open(prefs_path, 'w') as f:
            json.dump(prefs_dict, f)


options = webdriver.ChromeOptions()
set_download_directory(profile_path, profile_name, download_path) # Edit the Preferences first before loading the profile. 
options.add_argument(f'user-data-dir={profile_path}')
options.add_argument(f'--profile-directory={profile_name}')
driver = webdriver.Chrome(chrome_options=options)

Upvotes: 1

Related Questions