user3294195
user3294195

Reputation: 1828

Python Selenium Webdriver - Dynamically change download directory

To explicitly define the download directory prior to defining the selenium webdriver we use the following code:

chromeOptions = webdriver.ChromeOptions()
prefs = {"download.default_directory" : "C:/data/cline"}
chromeOptions.add_experimental_option("prefs",prefs)
chromePath = "path to chromedriver"

driver = selenium.webdriver.chrome.webdriver.WebDriver(executable_path=chromePath, port=0,    chrome_options=chromeOptions, service_args=None, desired_capabilities=None,   service_log_path=None)

I want to download a number of files, each to a different (newly created) directory. Is it possible to change the download directory after defining driver?

Upvotes: 11

Views: 7882

Answers (4)

Stefano Ferrari
Stefano Ferrari

Reputation: 1

A possible solution can be setting a symlink as the default download directory.

You can combine the solution in Modifying a symlink in python and the setting of the custom download directory (it can depend on the OS context, I am using Ubuntu 22.04).

In the minimal example below, two files are downloaded in two different directories. I used the symlink function (see the above reference) to avoid race conditions, but os.replace or os.rename can probably be used in simpler situations.

DRIVER_PATH = '/usr/bin/chromedriver'
DEFAULT_DOWNLOAD_PATH = os.path.expanduser('~/Downloads')
DOWNLOAD_PATH = os.path.abspath('./Downloads')

def symlink(target, link_name, overwrite=False):
    '''
    Create a symbolic link named link_name pointing to target.
    If link_name exists then FileExistsError is raised, unless overwrite=True.
    When trying to overwrite a directory, IsADirectoryError is raised.
    https://stackoverflow.com/questions/8299386/modifying-a-symlink-in-python/
    '''
    pass

#main
if __name__ == '__main__':

    service = Service(DRIVER_PATH)
    options = webdriver.ChromeOptions()
    prefs = {"download.default_directory": DOWNLOAD_PATH,
                 "savefile.default_directory": DOWNLOAD_PATH}
    options.add_experimental_option("prefs", prefs)
    browser = webdriver.Chrome(service=service, options=options)

    os.mkdir('./t1')
    symlink('./t1', DOWNLOAD_PATH, overwrite=True)
    browser.get('https://archive.org/download/knotssplicesandr13510gut/13510.zip')
    os.mkdir('./t2')
    symlink('./t2', DOWNLOAD_PATH, overwrite=True)
    browser.get('https://archive.org/download/knotssplicesandr13510gut/13510-h.zip')

Upvotes: 0

calfzhou
calfzhou

Reputation: 1360

I just tried this way to change download folder during webdriver running:

driver.command_executor._commands['send_command'] = (
    'POST', '/session/$sessionId/chromium/send_command')
download_path = 'PATH/TO/MY/CURRENT/DESIRED'
params = {
    'cmd': 'Page.setDownloadBehavior',
    'params': { 'behavior': 'allow', 'downloadPath': download_path }
}
driver.execute("send_command", params)

or:

download_path = 'PATH/TO/MY/CURRENT/DESIRED'
params = { 'behavior': 'allow', 'downloadPath': download_path }
driver.execute_cdp_cmd('Page.setDownloadBehavior', params['params'])

It won't change Chrome's default download location setting, but will save file to the new given folder (will create if not exists) in subsequent downloads.

Upvotes: 2

Mark Beebe
Mark Beebe

Reputation: 31

I have been unable to figure out how to do this and have used a work around. Instead of changing the webDriver download directory on the fly, the below solution just moves the file that you download.

ExperimentsWithCode Gave the Answer Here. Below is part of his solution

def move_to_download_folder(downloadPath, newFileName, fileExtension):
    got_file = False   
    ## Grab current file name.
    while got_file = False:
        try: 
            currentFile = glob.glob(DOWNLOAD_PATH+"*"+fileExtension)
            got_file = True

        except:
            print "File has not finished downloading"
            time.sleep(20)

    ## Create new file name
    fileDestination = downloadPath+newFileName+fileExtension

    os.rename(currentFile, fileDestination)

    return

Upvotes: 3

i.krivosheev
i.krivosheev

Reputation: 397

driver.set_preference("download.default_directory", "path/")

Try this variant.

Upvotes: -2

Related Questions