I know this question has been asked before...but I've tried multiple approaches and for some reason anything I download from the driver keeps going to my Downloads folder.
Basically I navigate to a website and download something by clicking a download link like so:
result.click()
This downloads the file fine. But I want to download it to a specific directory. I've tried doing these approaches to change the download directory:
driver = webdriver.Firefox()
profile = webdriver.FirefoxProfile()
driver.command_executor._commands["SET_CONTEXT"] = ("POST", "/session/$sessionId/moz/context")
driver.execute("SET_CONTEXT", {"context": "chrome"})
driver.execute_script("""
Services.prefs.setBoolPref('browser.download.useDownloadDir', true);
Services.prefs.setStringPref('browser.download.dir', arguments[0]);
""", directory)
driver.execute("SET_CONTEXT", {"context": "content"})
and
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", directory)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip")
Where directory
is my desired location.
Neither of these worked...can anyone explain why or show me how to actually achieve this?
Thanks
To change install location, click on Customize installation , then Next and enter C:\python35 (or another appropriate location) as the install location. If you didn�t check the Add Python 3.5 PATH option earlier, check Add Python to environment variables .
To make Firefox work with Python selenium, you need to install the geckodriver. The geckodriver driver will start the real firefox browser and supports Javascript. Take a look at the selenium firefox code. First import the webdriver, then make it start firefox.
Step 1: Selenium FirefoxDriver or Selenium GeckoDriver can be downloaded from the official GitHub repository of Mozilla. Go to the link and scroll towards the bottom of the page. Open the Assets menu and download the Selenium FirefoxDriver respective to your operating system. Step 2: Extract the downloaded file.
As of 2021 the FirefoxProfile
class used in earlier answers is deprecated, for the new selenium.webdriver.firefox.options.Options
:
from selenium.webdriver.firefox.options import Options
options = Options()
options.set_preference("browser.download.folderList", 2)
options.set_preference("browser.download.manager.showWhenStarting", False)
options.set_preference("browser.download.dir", "./downloads")
options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip")
driver = webdriver.Firefox(options=options)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With