使用Selenium Chrome驱动程序自动“另存为PDF”时缺少元素

时间:2019-03-01 11:44:07

标签: python selenium-webdriver selenium-chromedriver

我正在尝试使用硒(chrome)网络驱动程序自动保存使用pdftohtmlEXhttps://github.com/coolwanglu/pdf2htmlEX)创建的PDF文件。

除了图形的标题外,几乎可以使用,有时甚至丢失了部分图形。

手动保存:

Manually saved

使用硒和Chrome网络驱动程序自动保存: Saved using selenium & chromedriver

这是我的代码(您需要与此脚本位于同一文件夹中的Chrome浏览器驱动程序(http://chromedriver.chromium.org/downloads)):

import json
from selenium import webdriver

# print settings: save as pdf, 'letter' formatting
appState = """{
    "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local"
        }
    ],
    "mediaSize": {
        "height_microns": 279400,
        "name": "NA_LETTER",
        "width_microns": 215900,
        "custom_display_name": "Letter"
    },
    "selectedDestinationId": "Save as PDF",
    "version": 2
}"""

appState = json.loads(appState)
profile = {"printing.print_preview_sticky_settings.appState": json.dumps(appState)}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)
# Enable automatically pressing the print button in print preview
# https://peter.sh/experiments/chromium-command-line-switches/
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome('./chromedriver', options=chrome_options)
driver.get('http://www.deeplearningbook.org/contents/intro.html')
driver.execute_script('window.print();')
driver.quit()

有时,当我手动打印时也会发生这种情况。但是,如果我随后更改任何打印选项,则无论我进一步启用/禁用了哪些选项,预览都会重新加载,并且图像标题会再次出现并停留在该位置。

Chrome printing settings

到目前为止我尝试过的事情:

  • 该网站的http://chromedriver.chromium.org/downloads的不同Chrome浏览器网络驱动程序版本(71、72、73)
  • 通过在appState中添加““ isCssBackgroundEnabled”:true“来启用背景图形

1 个答案:

答案 0 :(得分:4)

因此,在各地的纠缠中,我偶然遇到了解决方案。我真的不明白为什么,但是启用“ PrintBrowser模式”(“启用PrintBrowser模式,所有内容都呈现为打印状态。”)解决了该问题。这可能与CSS正确加载有关。

我只需要添加chrome_options.add_argument('--enable-print-browser'),所有元素都在那里!

相关问题