1

How do i change the default download directory in the current running driver session? as i need to change the download directory many times to store particular file at particular location using 'for' loop.

below are the code which the tried to change the default directory of already running chrome driver session:

os.getcwd()
os.chdir("C:\\Site_tracker\\Output")
direc = ['S1_2g3g4g', 'S2_2g3g4g','S3_2g3g4g']
for i in direc:
    if not os.path.exists(i):
        os.makedirs(i)
    download_path=os.path.abspath(i)
    print(download_path)
    chr_Options.add_experimental_option('prefs', {
    "download.default_directory": "download_path", #Change default directory for downloads
    "download.prompt_for_download": False, #To auto download the file
    "download.directory_upgrade": True,
    "plugins.always_open_pdf_externally": True})
    driver1=webdriver.Chrome(chrome_options=chr_Options)

1 Answers1

0

Download directory is usually set when you create a browser instance by option setting "download.default_directory" like described here: How to use chrome webdriver in selenium to download files in python? or as you have in snippet.

If you want to store files to different directories during one session, you have some choices, but the one, which I choose, because in same task I also need to change filenames, was store file to local /tmp directory, rename and move it to final place.

import os
import shutil

CWD = os.getcwd()
TMP_DIR = CWD + "/tmpf"        # directly downloaded files
if not os.path.isdir(TMP_DIR):
    os.mkdir(TMP_DIR)
DWN_DIR = CWD + '/downloaded_files'   # renamed files from TMP_DIR
if not os.path.isdir(DWN_DIR):
    os.mkdir(DWN_DIR)

in prefs: "download.default_directory" : TMP_DIR, then

file_to_download.click()

old_name = os.listdir("./tmpf")[0]
old_file_name = TMP_DIR + "/" + old_name
new_file_name = DWN_DIR + '/' +  "SPECIFIC_Prefix_" + old_name.lower().replace(" ","_")
shutil.move(old_file_name, new_file_name) 
print("File downloaded and moved to: ", new_file_name)
Mintaka
  • 89
  • 1
  • 3