且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Selenium(Python)中将打开的页面保存为pdf

更新时间:2022-11-19 11:25:12

答案 此处,当我的操作系统中没有任何其他打印机设置时工作.但是当我有另一台默认打印机时,这不起作用.

The answer here, worked when I did not have any other printer setup in my OS. But when I had another default printer, this did not work.

我不明白怎么做,但以这种方式做一些小的改变似乎是可行的.

I don't understand how, but making small change this way seems to work.

from selenium import webdriver
import json

chrome_options = webdriver.ChromeOptions()
settings = {
       "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
        "selectedDestinationId": "Save as PDF",
        "version": 2
    }
prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings)}
chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')
CHROMEDRIVER_PATH = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=CHROMEDRIVER_PATH)
driver.get("https://google.com")
driver.execute_script('window.print();')
driver.quit()