python - 使用 selenium chrome 驱动时自动丢失元素 'Save as PDF'

标签 python selenium-webdriver selenium-chromedriver

我正在尝试使用 selenium (chrome) webdriver 自动保存使用 pdftohtmlEX ( https://github.com/coolwanglu/pdf2htmlEX ) 创建的 PDF 文件。

它几乎可以工作,除了数字的标题,有时甚至部分数字会丢失。

手动保存:

Manually saved

使用 selenium 和 chrome webdriver 自动保存: Saved using selenium & chromedriver

这是我的代码(您需要将 chromium webdriver ( 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

到目前为止我尝试了什么:

最佳答案

所以,通过摆弄,我偶然得到了解决方案。我真的不明白为什么,但是启用“PrintBrowser 模式”(“启用 PrintBrowser 模式,在该模式下一切都呈现为打印。”)解决了这个问题。这可能或可能与 CSS 正确加载有关。

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

关于python - 使用 selenium chrome 驱动时自动丢失元素 'Save as PDF',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54943980/

相关文章:

firefox - 无法单击存在但不可见的输入类型 ="button"

java - 无法实例化类错误消息 - 在 testNG 中

excel - 如何使用 Selenium 包装器从带有 vba 的 html 中获取特定元素

WebDriver - Chrome - 排除开关列表

python - 根据数据框中的条件对值进行排序

python - 为什么这个 SQLAlchemy 示例将更改提交到数据库?

node.js - 覆盖 Date 构造函数执行脚本

python - 使用请求将 CURL 命令转换为 Python

python - Python中除了实例方法、静态方法、类方法之外,还有第四种方法吗?

cucumber - 使用弹出框: unable to locate element,时出错