4

I'm wondering how can I update/change download location in selenium once I started driver?

it is not problem to set download dir during creation of profile and initiation of webdriver. The problem appears after initiation of webdriver to change directory depending on data type.

For example -if dl doc is word save in Docs\Word -if dl doc is pdf save in Docs\pdf

this is my code

profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.dir', os.getcwd())
profile.set_preference("browser.download.folderList", 2)
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/download,application/octet-stream,application/pdf')
profile.update_preferences()
driver = webdriver.Firefox(firefox_profile=profile)
driver.delete_all_cookies()
sleep(10)
# this part doesn't work
driver.profile.set_preference('browser.download.dir',"{0}\{1}".format(os.getcwd(),"Docs"))
driver.profile.update_preferences()
PythonMan
  • 787
  • 10
  • 18
  • I don't think it is possible through Selenium, see discussion here [https://groups.google.com/forum/#!topic/selenium-users/_uJeXWJHAaI] – Sodium Jan 11 '18 at 18:39
  • huh I will try several more combinations after that I will have to make a workaround. – PythonMan Jan 11 '18 at 18:43
  • Possible duplicate of [Downloading file to specified location with Selenium and python](https://stackoverflow.com/questions/25251583/downloading-file-to-specified-location-with-selenium-and-python) – Nimish Bansal Jan 11 '18 at 18:46
  • it not duplicate...in that post he didn't know how to set download location using selenium. I'm looking to change download dir after initiate of driver that already has another dl dir location. ;) – PythonMan Jan 11 '18 at 19:13

1 Answers1

9

With Firefox it's possible to change the preferences at run-time with a scrip injection once the context is set to chrome:

def set_download_dir(driver, directory):
  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"})
Florent B.
  • 41,537
  • 7
  • 86
  • 101