79407094

Date: 2025-02-02 18:31:07
Score: 0.5
Natty:
Report link

A possible solution can be setting a symlink as download default 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')
Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Stefano Ferrari