使用 Selenium 和 ChromeDriver,自动缩放打印页面的尺寸

TAH*_*TAH 4 python printing selenium chromium selenium-chromedriver

我正在编写一个脚本来自动打印 Chrome 中的一组网页。如果我要手动打印它们,我会从“比例”下拉列表中选择“自定义”,然后在下面的输入字段中输入 50。

在此输入图像描述

当我使用 Selenium 和 ChromeDriver 自动批量打印这些页面时,我无法弄清楚要传入哪些参数来复制此设置。

appState = { "recentDestinations": [{
                "id": "Save as PDF",
                "origin": "local",
                "account": "",
                "printing.scaling": 'Custom', # <== Does it go here?
             }],
             "selectedDestinationId": "Save as PDF",
             "version": 2,
             "printing.scaling": 'Custom',  # <== Or here?
           }
profile = { 'printing.print_preview_sticky_settings.appState': json.dumps(appState),
            'printing.print_header_footer': False,

            # So many different versions of things I have tried :-(
            'printing.scaling': 'Custom',
            'printing.scaling_type': 'Custom',
            'print_preview.scaling': 'Custom',
            'print_preview.scaling_type': 'Custom',
            'printing.custom_scaling': True,
            'printing.fit_to_page_scaling': 50,
            'printing.page_scaling': True,
          }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)
br = webdriver.Chrome(options=chrome_options)
Run Code Online (Sandbox Code Playgroud)

上面显示的所有不同选项都是在阅读大量 Chromium 源代码并试图获得提示后的猜测。

https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc?view=markup https://chromium.googlesource.com/chromium/src/+/master/printing/print_job_constants .cc https://chromium.googlesource.com/chromium/src/+/master/printing/print_job_constants.h

我没有线索了。接下来我可以尝试什么?

ask*_*tor 5

经过一番查找和尝试,我终于找到了解决方案!该设置位于 appState 字典中,称为“scalingType”,但它是一个枚举,令人烦恼的是,它似乎只接受一个数字,这些数字是在此处(Github镜像)此处(googlesource)定义的。3 为您提供自定义缩放,然后您可以在“缩放”设置(这是一个字符串!)中定义它。所以我的设置现在看起来像:

chrome_options = webdriver.ChromeOptions()
appState = {"recentDestinations": [{"id": "Save as PDF", "origin": "local", "account": ""}],
            "selectedDestinationId": "Save as PDF",
            "version": 2,
            "isHeaderFooterEnabled": False,
            "isLandscapeEnabled": True,
            "scalingType": 3,
            "scaling": "141"}
prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(appState),
         'savefile.default_directory': BASE_DIR}
chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('kiosk-printing')

driver = webdriver.Chrome(f'{BASE_DIR}\\chromedriver.exe', options=chrome_options)
Run Code Online (Sandbox Code Playgroud)

缩放类型的当前选项有:

  • 0:默认
  • 1:适合页面
  • 2:适合纸张
  • 3:定制

但我在“适合”选项中都没有取得任何成功。

更一般地说,大多数设置/选项可以通过查看chromium 源文件和/或其包含文件夹来确定。