Chrome WebDriver+Selenium Python打印时无法保存文件的问题
Chrome 114升级后Selenium Kiosk打印PDF无法保存的解决方案
问题背景
此前使用Python+Selenium的--kiosk-printing模式,自动将含window.print()的网页保存为PDF,Chrome 113版本完全正常。升级至Chrome 114并同步更新WebDriver后,打印对话框显示"正在打印",但PDF文件未保存到指定目录,已验证目录路径、权限均无问题。
用户原代码
from bs4 import BeautifulSoup import html2text import time import os import glob import json from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.keys import Keys from datetime import date from datetime import datetime import pandas as pd from selenium.webdriver.chrome.options import Options PATH = "/usr/local/bin/chromedriver" s = Service(PATH) # 冗余代码:Options类已自带add_experimental_option方法,无需自行定义 self._experimental_options = {} def add_experimental_option(self, name, value): """ Adds an experimental option which is passed to chrome. Args: name: The experimental option name. value: The option value. """ self._experimental_options[name] = value print_settings = { "recentDestinations": [{ "id": "Save as PDF", "origin": "local", "account": "", }], "selectedDestinationId": "Save as PDF", "version": 2 } prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(print_settings), "download.prompt_for_download": False, "profile.default_content_setting_values.automatic_downloads": 1, "download.default_directory": "/Users/seth/Downloads/pdfs", "savefile.default_directory": "/Users/seth/Downloads/pdfs", "download.directory_upgrade": True, "safebrowsing.enabled": True} options = Options() options.add_experimental_option('prefs', prefs) options.add_argument('--kiosk-printing') driver = webdriver.Chrome(service=s, options=options) # 加载打印页面 driver.get("https://www.heresmyprintingpage.com/1.htm")
问题原因
Chrome 114对打印预览的偏好设置结构进行了调整,旧版本的print_settings参数已无法正确触发自动保存逻辑;同时用户代码中存在冗余的自定义方法,可能干扰Options的正常配置。
解决方案
1. 移除冗余代码
删除自定义的add_experimental_option函数及self._experimental_options变量,Options类原生支持该方法,无需重复定义。
2. 更新打印配置结构
调整print_settings参数,补充Chrome 114要求的打印属性;同时添加默认目标选择规则,强制指定"保存为PDF"。
3. 确保目录存在
添加代码确保目标保存目录已创建,避免因目录不存在导致保存失败。
修改后的完整代码
from bs4 import BeautifulSoup import html2text import time import os import glob import json from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.keys import Keys from datetime import date from datetime import datetime import pandas as pd from selenium.webdriver.chrome.options import Options # 定义PDF保存目录 PDF_DIR = "/Users/seth/Downloads/pdfs" # 确保目录存在 os.makedirs(PDF_DIR, exist_ok=True) PATH = "/usr/local/bin/chromedriver" s = Service(PATH) # 更新Chrome 114兼容的打印配置 print_settings = { "recentDestinations": [ { "id": "Save as PDF", "origin": "local", "account": "" } ], "selectedDestinationId": "Save as PDF", "version": 2, "isLandscape": False, # 根据需求调整横竖版 "marginsType": 0, # 0=默认边距,1=无边距,2=最小边距 "scaling": 100, "scalingType": 3, "scalingTypePdf": 3 } prefs = { "printing.print_preview_sticky_settings.appState": json.dumps(print_settings), "download.prompt_for_download": False, "profile.default_content_setting_values.automatic_downloads": 1, "download.default_directory": PDF_DIR, "savefile.default_directory": PDF_DIR, "download.directory_upgrade": True, "safebrowsing.enabled": True, # 添加默认打印目标规则,强制选择保存为PDF "printing.default_destination_selection_rules": { "kind": "local", "namePattern": "Save as PDF" } } options = Options() options.add_experimental_option('prefs', prefs) options.add_argument('--kiosk-printing') # 可选:禁用扩展和弹窗拦截,避免干扰 options.add_argument('--disable-extensions') options.add_argument('--disable-popup-blockers') driver = webdriver.Chrome(service=s, options=options) # 加载打印页面 driver.get("https://www.heresmyprintingpage.com/1.htm") # 可选:等待页面加载完成后再触发打印(如果页面print是自动触发可忽略) time.sleep(3)
额外验证步骤
- 确认ChromeDriver版本与Chrome浏览器版本完全一致(Chrome 114对应ChromeDriver 114.x.x.x)
- 检查目标目录的读写权限,确保运行脚本的用户有写入权限
- 若仍有问题,可尝试添加
--headless=new参数(Chrome 112+的新无头模式),避免界面交互干扰
内容的提问来源于stack exchange,提问作者Seth Kramer
相关产品推荐
相关产品推荐

