首页 > 解决方案 > 使用 Selenium 时,我无法让 Chrome 默认保存为 PDF

问题描述

我正在尝试使用 Python、Selenium 和 Chrome 将一些网页保存为 PDF,但我无法让打印机默认使用 Chrome 的内置“另存为 PDF”选项。

我已经在网上的各个地方找到了如何做到这一点的例子,包括人们在 Stack Overflow 上提出的问题,但是他们都在实施它的方式不起作用,我不确定最近是否发生了一些变化Chrome 的版本,或者如果我做错了什么(例如,这是一个具有以下设置的页面:Missing elements when using selenium chrome driver to automatically 'Save as PDF')。

我只在此代码中包含了默认下载位置更改,以验证它是否接受任何更改 - 如果您从该页面下载 Python 安装之一,它将下载到新位置而不是标准下载文件夹,因此 Chrome 似乎接受这些变化。

问题似乎是选项“selectedDestinationID”,它似乎没有做任何事情。

from selenium import webdriver
import time
import json

chrome_options = webdriver.ChromeOptions()

app_state = {
        'recentDestinations': [{
            'id': 'Save as PDF',
            'origin': 'local'
        }],
        'selectedDestinationId': 'Save as PDF',
        'version': 2
    }



prefs = {
    'printing.print_preview_sticky_settings.appState': json.dumps(app_state),
    'download.default_directory': 'c:\\temp\\seleniumtesting\\'
    }
chrome_options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(executable_path='C:\\temp\\seleniumtesting\\chromedriver.exe', options=chrome_options)

driver.get('https://www.python.org/downloads/release/python-373/')

time.sleep(25)
driver.close()

页面启动后,按 ctrl+p 会调出打印页面,但默认为默认打印机。如果我在标准 Chrome 安装中打开同一页面,则默认打印为 PDF。我想达到可以添加信息亭打印然后调用 window.print() 的地步,但到目前为止所做的只是将它发送到实际的纸质打印机。

感谢任何人都可以提供的任何帮助。我很难过,此时手动保存所有这些可能会更快。

标签: pythonselenium

解决方案


似乎如果您配置了网络打印机,它们会在打开对话框后加载并覆盖您的 selectedDestination。

有一个偏好“printing.default_destination_selection_rules”似乎可以解决。

prefs = {
    "printing.print_preview_sticky_settings.appState": json.dumps(app_state),
    "download.default_directory": "c:\\temp\\seleniumtesting\\".startswith(),
    "printing.default_destination_selection_rules": {
        "kind": "local",
        "namePattern": "Save as PDF",
    },
}

https://chromium.googlesource.com/chromium/src/+/master/chrome/common/pref_names.cc#1318 https://www.chromium.org/administrators/policy-list-3#DefaultPrinterSelection


推荐阅读