Downloading a file at a specified location through python and selenium using Chrome driver
Asked Answered
C

12

52

I am trying to automatically download some links through selenium's click functionality and I am using a chrome webdriver and python as the programming language. How can I select the download directory through the python program so that it does not get downloaded in the default Downloads directory. I found a solution for firefox but there the download dialog keeps popping up every time it clicks on the link which does not happen in Chrome.

Cankerous answered 11/2, 2016 at 5:58 Comment(2)
Go to chrome settings and check Ask to save each file before downloadingTadtada
Possible duplicate of setting Chrome preferences w/ Selenium Webdriver in PythonUnderline
A
27

Update 2018:

Its not valid Chrome command line switch, see the source code use hoju answer below to set the Preferences.

Original:

You can create a profile for chrome and define the download location for the tests. Here is an example:

from selenium import webdriver

options = webdriver.ChromeOptions() 
options.add_argument("download.default_directory=C:/Downloads")

driver = webdriver.Chrome(chrome_options=options)
Abby answered 11/2, 2016 at 7:48 Comment(6)
Why do you need to import Options?Dreary
This does not appear to work. Perhaps Chromedriver's interface has changed? hoju's response appears to work now.Sissified
it's not work if we want download a video..video show on chrome instead of download...How download video now?Molecule
It's not work for me in mac, just try ans below: prefs = {'download.default_directory' : '/path/to/dir'}; chrome_options.add_experimental_option('prefs', prefs)Bayer
This answer is deprecated. Acceptable answer should be changed to Hoju's.Haymo
How to change the default directory after Webdriver started? How to get the name of file downloaded?Zennie
M
136

I found the accepted solution didn't work, however this slight change did:

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : '/path/to/dir'}
chrome_options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
Maggiore answered 4/5, 2017 at 17:51 Comment(9)
Thanks! This really solve my problem. However, it seems not working for relative path. e.g. D:/ddd works while ./tmp does not. The ./tmp (relative path) ends up poping up a dialog for me to manually choose the directory...Viradis
Is there a way to change download path while on current session, similar to how you click Chrome Settings->Download ? The answer I saw always incur building new option + new driver + get a whole new session . I would wish not to close the current session, since my folder separation based on each item in a drop-down list and there's no need to reload a new page. There are thousands of items in that drop-down; the accepted method means closing and loading the page thousands times.Methadone
It's works! Mac google chrome 78.0.3904.97 and chromedriver 2.40Bayer
How to change the default directory after WebDriver started?Zennie
How to get the name of file downloaded?Zennie
chrome_options is deprecatedDisembark
Doesn't work for me and I am getting a download error. Code works fine for default download directory though (Windows)Nicholle
Code worked for me and I don't get any down error. Also Chrome_Options is deprecated so I used options instead earlier the path was C:/Users/myusname/drivers/DownloadFiles I changed it to C:\Users\myusname\drivers\DownloadFiles\\ downloadFilepath = r"C:\Users\myusname\drivers\DownloadFiles\\"; chrome_options = webdriver.ChromeOptions() prefs = {"download.default_directory" : downloadFilepath} options.add_experimental_option('prefs', prefs) driver=webdriver.Chrome(executable_path=chromedriver,options=options) Solution: https://mcmap.net/q/328958/-selenium-webdriver-in-python-files-download-directory-change-in-chrome-preferencesNicholle
@Methadone is this possible. Did you find the solution ?Bedtime
A
27

Update 2018:

Its not valid Chrome command line switch, see the source code use hoju answer below to set the Preferences.

Original:

You can create a profile for chrome and define the download location for the tests. Here is an example:

from selenium import webdriver

options = webdriver.ChromeOptions() 
options.add_argument("download.default_directory=C:/Downloads")

driver = webdriver.Chrome(chrome_options=options)
Abby answered 11/2, 2016 at 7:48 Comment(6)
Why do you need to import Options?Dreary
This does not appear to work. Perhaps Chromedriver's interface has changed? hoju's response appears to work now.Sissified
it's not work if we want download a video..video show on chrome instead of download...How download video now?Molecule
It's not work for me in mac, just try ans below: prefs = {'download.default_directory' : '/path/to/dir'}; chrome_options.add_experimental_option('prefs', prefs)Bayer
This answer is deprecated. Acceptable answer should be changed to Hoju's.Haymo
How to change the default directory after Webdriver started? How to get the name of file downloaded?Zennie
H
17

the exact problem I also have faced while trying to do exactly same what you want to :)

For chrome:

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
prefs = {"profile.default_content_settings.popups": 0,
             "download.default_directory": 
                        r"C:\Users\user_dir\Desktop\\",#IMPORTANT - ENDING SLASH V IMPORTANT
             "directory_upgrade": True}
options.add_experimental_option("prefs", prefs)
browser=webdriver.Chrome(<chromdriver.exe path>, options=options)

For Firefox: follow this blog for the answer: https://srirajeshsahoo.wordpress.com/2018/07/26/how-to-bypass-pop-up-during-download-in-firefox-using-selenium-and-python/

The blog says all about the pop-up and downloads dir and how to do

Hargrave answered 15/8, 2019 at 14:16 Comment(0)
C
5

Using prefs solved my problem

path = os.path.dirname(os.path.abspath(__file__))
prefs = {"download.default_directory":path}
options = Options()
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome('../harveston/chromedriver.exe',options = options)
Cardialgia answered 31/7, 2020 at 10:21 Comment(0)
I
4

This worked for me on Chrome v81.0.4044.138

preferences = {
                "profile.default_content_settings.popups": 0,
                "download.default_directory": os.getcwd() + os.path.sep,
                "directory_upgrade": True
            }

chrome_options.add_experimental_option('prefs', preferences)
browser = webdriver.Chrome(executable_path="/usr/bin/chromedriver", options=chrome_options)
Ilmenite answered 8/5, 2020 at 23:1 Comment(4)
This one is working also on Chrome 80.0.3987.149. I tried the other answers above and they didn't work on my Ubuntu machine. Thanks @IlmeniteSorce
ditto for working with 81.0.4044.69. needs add of chrome_options = webdriver.ChromeOptions()Strade
also: webdriver.Chrome(options=blah) supercedes webdriver.Chrome(chrome_options=blah) I would use a variable name other than chrome_options or options to avoid confusion.Strade
The chrome_options is deprecated now. And if I use the options as mentioned in previous comment does not work(I wonder why it is not working). The above code works in my Mac of Chrome Version 83Supposed
E
1

If you are using linux distribution

Use this code

prefs = {'download.prompt_for_download': False,
         'download.directory_upgrade': True,
         'safebrowsing.enabled': False,
         'safebrowsing.disable_download_protection': True}

options.add_argument('--headless')
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome('chromedriver.exe', chrome_options=options)
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
driver.desired_capabilities['browserName'] = 'ur mum'
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': r'C:\chickenbutt'}}
driver.execute("send_command", params)
Eden answered 28/9, 2018 at 2:47 Comment(0)
E
1

I see that many people have the same problem, just add the backslash at the end

op = webdriver.ChromeOptions()
prefs = {'download.default_directory' : 'C:\\Users\\SAJComputer\\PycharmProjects\\robot-test\\'}
op.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(executable_path=driver_path , options=op)
Error answered 26/9, 2021 at 16:41 Comment(1)
Instead of using double backslash in the path you can convert the path as raw string using r'C:\Users\SAJComputer\PycharmProjects\robot-test'Edmead
C
1

Update 2022:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()

prefs = {"download.default_directory" : "C:\YourDirectory\Folder"}

options.add_experimental_option("prefs", prefs)

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
Corenda answered 1/8, 2022 at 13:19 Comment(1)
What is Service in this case? it not defined beforeSurtax
A
0

To provide download directory and chrome's diver executable path use the following code.

from selenium import webdriver
options = webdriver.ChromeOptions() 
options.add_argument("download.default_directory=C:/Your_Directory")
driver = webdriver.Chrome(options=options ,executable_path='C:/chromedriver')

change the path in your code accordingly.

Ahearn answered 4/6, 2019 at 6:11 Comment(0)
M
0

Below code snippet holds good for Windows/linux/MacOs distro:

    downloadDir = f"{os.getcwd()}//downloads//"
    # Make sure path exists.
    Path(downloadDir).mkdir(parents=True, exist_ok=True)
    
    # Set Preferences.
    preferences = {"download.default_directory": downloadDir,
                   "download.prompt_for_download": False,
                   "directory_upgrade": True,
                   "safebrowsing.enabled": True}

    chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_argument("--window-size=1480x560")
    chromeOptions.add_experimental_option("prefs", preferences)

    driver = webdriver.Chrome(DRIVER_PATH, options=chromeOptions)
    driver.get(url)
    time.sleep(10)
    driver.close()
Misgive answered 23/11, 2021 at 17:27 Comment(0)
M
0

It's for relative path:

download_directory = os.path.abspath('./tmp')
chrome_options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : download_directory}
chrome_options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(options=chrome_options)
Murraymurre answered 20/12, 2023 at 18:40 Comment(0)
M
-7

This is non code level solution with no chrome profiling/options settings.

If you are using script only on your local machine then use this solution

Click on Menu -> Setting -> Show advanced settings... -> Downloads

Now uncheck

Ask where to save each file before downloading

enter image description here

Hope it will help you :)

Matildematin answered 11/2, 2016 at 6:23 Comment(7)
This question is about controlling chrome through an automated system called selenium. You answered as if he asked about controlling chrome manually.Kuhlman
It's a one time configuration you have to made and yes it's a solution tooMatildematin
This is actually a valid and working answer. It worked perfectly for me.Chorizo
Please rate this answer .. I need to remove it if it will have negative ratingMatildematin
Shubam had answered it well. Set your chrome profile's default directory and then it will be the solution.Topmost
The goal is to change this configuration through Selenium and not manually... the whole point of Selenium is to automatize.Haymo
Doesn’t you all guys just look it at a solution for local as I said and if not work then downgrade me .. so if I delete this working solution and no one else can see even if useful for them does that make all happy?Matildematin

© 2022 - 2024 — McMap. All rights reserved.