使用 Selenium/Python 多次更改 FirefoxProfile() 首选项 [英] Changing FirefoxProfile() preferences more than once using Selenium/Python
问题描述
所以我试图根据使用 Selenium 的链接将多个 excel 链接下载到不同的文件路径.
So I am trying to download multiple excel links to different file paths depending on the link using Selenium.
我能够设置 FirefoxProfile 以将所有链接下载到某个单一路径,但是当我尝试将不同的文件下载到不同的文件路径时,我无法即时更改路径.有没有人解决这个问题?
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.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)
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.
推荐答案
在 Linux 和 Mac 上,您可以将配置文件首选项设置为下载到作为另一个目录的符号链接的目录.然后,在运行 Selenium 驱动程序时,您可以使用 Python 中的 os
库将符号链接的目标更改为要下载文件的目录.
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.
代码大纲(没有try/except
等):
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")
这篇关于使用 Selenium/Python 多次更改 FirefoxProfile() 首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!