Python Selenium搭配Chrome配置文件时如何将打印PDF保存至指定目录
Selenium绑定自定义Chrome Profile时PDF打印路径异常问题
核心需求
- 基于Python+Selenium驱动Chrome实现浏览器自动化,调用浏览器原生打印功能将目标网页导出为PDF,保存到自定义指定目录
- 自动化运行时复用固定的Chrome用户配置(Profile)
核心故障
只要在驱动配置中绑定自定义Chrome Profile,通过打印功能生成的PDF就会自动存储到Chrome默认的Downloads下载目录,无法按照代码预设的自定义路径保存。
测试复现代码
import json from pathlib import Path from selenium import webdriver from selenium.webdriver.chrome.options import Options # 配置打印相关参数 save_to = str(Path(__file__).resolve().parent) # 期望的PDF保存路径 chrome_options: Options = webdriver.ChromeOptions() settings = { "recentDestinations": [{ "id": "Save as PDF", "origin": "local", "account": "", }], "selectedDestinationId": "Save as PDF", "version": 2, "isHeaderFooterEnabled": False } prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings), 'savefile.default_directory': save_to } chrome_options.add_experimental_option('prefs', prefs) chrome_options.add_argument('--kiosk-printing') # 配置Chrome Profile路径 chrome_profile_path = f"{os.curdir}/chrome_profiles/" chrome_profile_name = "Profile 1" chrome_options.add_argument(f"user-data-dir={chrome_profile_path}") chrome_options.add_argument(f"profile-directory={chrome_profile_name}") # 初始化驱动 driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver", options=chrome_options) driver.get('http://www.blankwebsite.com/') driver.execute_script('window.print();')
注:上述原测试代码存在遗漏
import os的依赖问题
已验证的对照测试结果
- 运行上述完整代码(即绑定自定义Profile)时,生成的PDF始终存储在默认Downloads文件夹
- 注释掉Profile绑定相关的配置代码(共4行):
# chrome_profile_path = f"{os.curdir}/chrome_profiles/" # chrome_profile_name = "Profile 1" # chrome_options.add_argument(f"user-data-dir={chrome_profile_path}") # chrome_options.add_argument(f"profile-directory={chrome_profile_name}")
打印生成的PDF可以正常保存到代码指定的路径
- 运行环境为Ubuntu 20.04系统
- 深入排查发现:目标Profile目录下的Preferences配置文件中固定存在
"savefile":{"default_directory":"/home/gelkin/Downloads"}字段,手动修改该字段值后重启Chrome,设置会被自动还原为默认下载路径
待解决目标
在保留固定Chrome Profile复用能力的前提下,实现打印PDF稳定存储到自定义指定目录。
内容的提问来源于stack exchange,提问作者gelkin
相关产品推荐
相关产品推荐

