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

前端 未结 4 2059
忘了有多久
忘了有多久 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:25

    Here is the solution I use with Windows :

    • First download the ChromeDriver here : http://chromedriver.chromium.org/downloads and install Selenium

    • Then run this code (based on the accepted answer, slightly modified to work on Windows):

      import json
      from selenium import webdriver
      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')
      browser = webdriver.Chrome(r"chromedriver.exe", options=chrome_options)
      browser.get("https://google.com/")
      browser.execute_script('window.print();')
      browser.close()    
      

提交回复
热议问题