Selenium Chrome:加载配置文件并更改下载文件夹-Python
OS:Win 10Selenium Chrome:加载配置文件并更改下载文件夹-Python,python,selenium,google-chrome,selenium-chromedriver,Python,Selenium,Google Chrome,Selenium Chromedriver,OS:Win 10 铬:81.0.4044.129 色度驱动器:81.0.4044.69 目标: 加载已配置扩展和首选项的现有配置文件,并指定默认下载位置 目的: 我想将图像保存到各自的文件夹名称中 挑战 如果指定要加载的Chrome配置文件,则无法更改默认下载文件夹。 代码片段: # Loading profile works! options = webdriver.ChromeOptions() options.add_argument(f'user-data-dir={profile
铬:81.0.4044.129
色度驱动器:81.0.4044.69 目标:
加载已配置扩展和首选项的现有配置文件,并指定默认下载位置 目的:
我想将图像保存到各自的文件夹名称中 挑战
如果指定要加载的Chrome配置文件,则无法更改默认下载文件夹。
代码片段:
# Loading profile works!
options = webdriver.ChromeOptions()
options.add_argument(f'user-data-dir={profile_path}')
options.add_argument(f'--profile-directory={profile_name}')
driver = webdriver.Chrome(chrome_options=options)
在创建驱动程序之前,是否可以加载配置文件并更改默认下载位置?
我认为没有一种方法既可以加载现有配置文件,也可以更改默认的目录选项。
因此,在加载配置文件之前,我使用了
json.loads
和json.dump
来修改“首选项”文件。我相信没有一种方法既可以加载现有的配置文件,也可以更改默认的目录选项。
因此,在加载配置文件之前,我使用了
json.loads
和json.dump
来修改“首选项”文件。你试过这篇文章的答案吗@安德烈亚哈萨尼:这是代码片段2。但这不允许我加载现有的配置文件。相反,代码片段2(以及那篇文章的答案)会创建一个临时概要文件。你试过这篇文章的答案吗@安德烈亚哈萨尼:这是代码片段2。但这不允许我加载现有的配置文件。相反,代码片段2(以及那篇文章的答案)将创建一个临时概要文件。
# Changing default download location works!
options = webdriver.ChromeOptions()
prefs = {"download.default_directory" : "C:/Downloads/Folder A"}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=options)
# This DOESN'T work! Default download location is not changed.
options = webdriver.ChromeOptions()
options.add_argument(f'user-data-dir={profile_path}')
options.add_argument(f'--profile-directory={profile_name}')
prefs = {"download.default_directory" : "C:/Downloads/Folder A"}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=options)
import json
from selenium import webdriver
# helper to edit 'Preferences' file inside Chrome profile directory.
def set_download_directory(profile_path, profile_name, download_path):
prefs_path = os.path.join(profile_path, profile_name, 'Preferences')
with open(prefs_path, 'r') as f:
prefs_dict = json.loads(f.read())
prefs_dict['download']['default_directory'] = download_path
prefs_dict['savefile']['directory_upgrade'] = True
prefs_dict['download']['directory_upgrade'] = True
with open(prefs_path, 'w') as f:
json.dump(prefs_dict, f)
options = webdriver.ChromeOptions()
set_download_directory(profile_path, profile_name, download_path) # Edit the Preferences first before loading the profile.
options.add_argument(f'user-data-dir={profile_path}')
options.add_argument(f'--profile-directory={profile_name}')
driver = webdriver.Chrome(chrome_options=options)