Josh Yang
Josh Yang

Reputation: 21

Changing FirefoxProfile() preferences more than once using Selenium/Python

So I am trying to download multiple excel links to different file paths depending on the link using Selenium.

I am able to set up the FirefoxProfile to download all links to a certain single path, but I can't change the path on the fly as I try to download different files into different file paths. Does anyone have a fix for this?

self.fp = webdriver.FirefoxProfile() self.ft.set_preferences("browser.download.folderList", 2) self.ft.set_preferences("browser.download.showWhenStarting", 2) self.ft.set_preferences("browser.download.dir", "C:\SOURCE FILES\BACKHAUL") self.ft.set_preferences("browser.helperApps.neverAsk.saveToDisk", ("application/vnd.ms-excel))

self.driver = webdriver.Firefox(firefox_profile = self.fp)

This code will set the path I want once. But I want to be able to set it multiple times while running one script.

Upvotes: 2

Views: 777

Answers (2)

Marijn
Marijn

Reputation: 1915

On Linux and Mac you can set the profile preferences to download to a directory that is a symbolic link to another directory. Then, while running the Selenium driver, you can change the destination of the symlink to the directory you want to download a file in, using the os library in Python.

Code outline (without try/except etc):

import os
from selenium import webdriver

DRIVER = "/usr/local/bin/geckodriver"

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.dir", "/your/symlink/name")
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "your/mime/type")

driver = webdriver.Firefox(firefox_profile=fp, executable_path=DRIVER)

# delete symlink before changing to prevent a FileExistsError when changing the link
if os.path.exists("/your/symlink/name"):
    os.unlink("/your/symlink/name")
# actually change/create the link
os.symlink("/real/target/directory", "/your/symlink/name")
# download the file
driver.get("https://example.com/file")

# set new target directory
os.unlink("/your/symlink/name")
os.symlink("/different/target/directory", "/your/symlink/name")
driver.get("https://example.com/otherfile")

Upvotes: 1

Stan
Stan

Reputation: 3461

You can define it only while initializing driver. So to do it with a new path you should driver.quit and start it again.

Upvotes: 0

Related Questions