how to save opened page as pdf in Selenium (Python)

前端 未结 4 2014
忘了有多久
忘了有多久 2021-02-04 16:20

Have tried all the solutions I could find on the Internet to be able to print a page that is open in Selenium in Python. However, while the print pop-up shows up, after a second

4条回答
  •  旧巷少年郎
    2021-02-04 17:21

    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()
    

提交回复
热议问题