如何用Python Selenium将打印预览Destination从Microsoft Print to PDF改为Save as PDF
解决Chrome打印预览中切换Destination并保存PDF的问题
方案一:通过Chrome配置直接自动保存PDF(推荐)
Chrome支持通过配置跳过打印预览弹窗,直接将网页导出为PDF,无需手动操作原生界面,这种方式稳定性更高。
修改你的代码如下,重点添加打印相关偏好设置和使用Chrome DevTools Protocol触发打印:
import time, os from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service def main(PDF_URL): options = webdriver.ChromeOptions() # 用os.path.join避免路径转义问题 download_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "download") os.makedirs(download_path, exist_ok=True) # 确保保存目录存在 # 基础浏览器配置 options.add_argument("--disable-popup-blocking") options.add_argument("--disable-notifications") options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_experimental_option('excludeSwitches', ['enable-logging']) # 添加打印与PDF保存的偏好设置 prefs = { 'download.default_directory': download_path, "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": True, # 配置默认打印目标为Save as PDF "printing.default_destination_selection_rules": { "kind": "local", "namePattern": "Save as PDF" }, "printing.print_preview_sticky_settings.appState": """{"recentDestinations":[{"id":"Save as PDF","origin":"local","account":""}],"selectedDestinationId":"Save as PDF","version":2}""" } options.add_experimental_option("prefs", prefs) # 添加命令行参数,启用无交互打印模式 options.add_argument('--kiosk-printing') browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) browser.maximize_window() browser.get(PDF_URL) browser.implicitly_wait(180) print("浏览器打开成功..") # 使用Chrome DevTools Protocol触发打印,自动保存为PDF browser.execute_cdp_cmd("Page.printToPDF", { "printBackground": True, "preferCSSPageSize": True, "saveAsPDF": True }) time.sleep(3) # 等待保存完成 browser.quit() if __name__ == "__main__": PDF_URL = "10.1055-s-2001-17364.pdf" main(PDF_URL)
方案二:用pyautogui模拟操作打印预览界面
如果必须通过打印预览界面操作,可利用pyautogui模拟键盘快捷键(比鼠标定位更稳定),在你原代码的time.sleep(5)之后添加以下代码:
# 模拟快捷键操作打印预览 pyautogui.hotkey('alt', 'd') # 切换到Destination下拉框 time.sleep(1) pyautogui.press('down') # 选中Save as PDF(若当前是Microsoft Print to PDF,按一次向下即可) time.sleep(0.5) pyautogui.press('enter') # 确认选择 time.sleep(1) pyautogui.hotkey('alt', 's') # 点击保存按钮
注意事项:
- 运行时Chrome窗口必须处于前台,pyautogui才能正确模拟操作
- 如果下拉选项顺序不同,需调整
pyautogui.press('down')的次数 - 根据实际情况调整
time.sleep()的等待时长,确保界面加载完成
内容的提问来源于stack exchange,提问作者Yug
相关产品推荐
相关产品推荐

