Selenium Chrome浏览器。加载配置文件并更改下载文件夹 - Python

问题描述 投票:0回答:1

OS: Win 10 Chrome: 81.0.4044.129 ChromeDriver: 81.0.4044.69

目标。 加载现有的配置文件,并配置扩展和偏好设置 AND 指定默认下载位置。

目的。 我想把图片保存到各自的文件夹中。

面临的挑战 如果我指定要加载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)
# 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)

是否可以在创建驱动程序之前同时加载配置文件和更改默认下载位置?

python selenium google-chrome selenium-chromedriver
1个回答
0
投票

我相信没有一种方法既能加载现有的配置文件,又能更改 default_directory 选项。因此,我使用了 json.loadsjson.dump 在加载配置文件之前修改 "偏好 "文件。

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)

© www.soinside.com 2019 - 2024. All rights reserved.