正在设置现有配置文件Selenium和Python的下载路径

x759pob2  于 2023-05-19  发布在  Python
关注(0)|答案(1)|浏览(122)

我的问题是当我传递profile作为选项时:

options.add_argument("--user-data-dir=C:\\Users\\shimon\\AppData\\Local\\Google\\Chrome\\User Data")
        options.add_argument("--profile-directory=Profile 3")

下载集路径似乎不受影响

prefs = {"download.default_directory": "C:\\Users\\shimon\\PycharmProjects\\project_2\\downloaded\\files"}
        options.add_experimental_option("prefs", prefs)

如果我删除侧写

options.add_argument("--profile-directory=Profile 3")

效果很好。有什么解决办法吗?找不到任何相关问题。

mrzz3bfm

mrzz3bfm1#

您可以尝试以下操作:

options = ChromeOptions()
current_directory = os.getcwd()
download_directory = f"{current_directory}/temp"

prefs = {
    "download.default_directory": download_directory,
    "download.prompt_for_download": False,  # To auto download the file
    "download.directory_upgrade": True,
    "plugins.always_open_pdf_externally": True,
}  # It will not show PDF directly in chrome}
options.add_experimental_option("prefs", prefs)
options.add_argument("--headless")

driver = # initialize driver

if not os.path.exists(download_directory):
    os.makedirs(download_directory)

params = {"behavior": "allow", "downloadPath": download_directory}
driver.execute_cdp_cmd("Page.setDownloadBehavior", params)

此外,您应该检查:
1.如果在路径中将\\替换为/有效(注意到Windows上有时会出现这个问题)
1.如果路径存在并且具有正确的权限

相关问题