【问题标题】:Automate print/save web page as pdf in chrome - python 2.7在 chrome 中自动打印/保存网页为 pdf - python 2.7
【发布时间】:2015-09-17 03:36:11
【问题描述】:

我正在尝试在 Chrome 中自动打印保存网页为 pdf。

我已经检查了 webbrowser 模块,但它似乎不是为此目的而设计的。

我探索了 wkhtmltopdf 作为替代方案,但下载文件时它似乎被病毒感染了。

感谢您的建议。

【问题讨论】:

标签: html python-2.7 automation pdf-generation


【解决方案1】:

这对我在 Windows 7 x64 上使用 Chrome 62.0.3202.94、ChromeDriver 2.33.506120、Selenium 3.4.3 和 Python 2.7.14 或 3.6.3 有效:

import json
from selenium import webdriver

appState = {
    "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local",
            "account": ""
        }
    ],
    "selectedDestinationId": "Save as PDF",
    "version": 2
}

profile = {'printing.print_preview_sticky_settings.appState': json.dumps(appState)}

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://www.google.com/')
driver.execute_script('window.print();')

【讨论】:

  • 不错的工作流程。你能指定路径并重命名创建的PDF吗?
  • @tao.hong:不,我在下载目录里找到最新的PDF,然后移动/重命名。
  • 同一脚本在headless 模式下不起作用。知道为什么吗?
  • 使用最新版Chrome(78.0.3904.108),需要将"account": ""添加到"recentDestinations"
【解决方案2】:

我找到了可能的解决方案。

代码将html文件保存为pdf,这是我的最终目标。

原帖是:

Python + Selenium + PhantomJS render to PDF

最好的。

【讨论】:

  • @MTuner,我想问你如何更改render = '''this.render("test.pdf")'''这一行,这样我就可以使用变量名(列表)和计数器来渲染多个页面并相应地保存文件名。
  • 请在你的答案中写一些有用的东西——除了链接。这样,如果链接断开,答案就没有用了。
猜你喜欢
  • 2018-09-13
  • 2011-12-28
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
  • 2020-01-13
  • 1970-01-01
相关资源
最近更新 更多