简体   繁体   中英

How to save web page as pdf automatically in Selenium python

I'm trying to save a web page as a PDF but all I get is a file name selection window. How to automatically enter a file name and save it?

settings = {
        "appState": {
            "recentDestinations": [{
                "id": "Save as PDF",
                "origin": "local",
                "account": "",
                "margin": 0,
                'size': 'auto'
            }],
            "selectedDestinationId": "Save as PDF",
            "version": 2,
            "margin": 0,
            'size': 'auto'
        }
    }
    #There is probably a lot of excess here, I tried to use everything that can help
    prefs = {'printing.print_preview_sticky_settings': json.dumps(settings),
             'profile.default_content_settings.popups': 0,
             'download.name': 'test.pdf', #It doesn't work(
             'download.default_directory': download_path,
             'savefile.default_directory': download_path,
             'download.prompt_for_download': False,
             "download.directory_upgrade": True,
             "safebrowsing_for_trusted_sources_enabled": False,
             "safebrowsing.enabled": True,
             "download.extensions_to_open": "",
             "plugins.always_open_pdf_externally": True,
             }
    options.add_experimental_option('prefs', prefs)
    options.add_argument('--kiosk-printing')
    driver = webdriver.Chrome(service=ser, options=options)
    driver.maximize_window()
    driver.get('url')

    driver.execute_script('window.print();')
    time.sleep(20)

I couldn't find a solution on the internet, I tried every possible option but it doesn't work for me.

There is no built-in function in Selenium that allows you to save a web page as a PDF. However, you can use a third-party tool, such as wkhtmltopdf, to accomplish this.

  1. Install wkhtmltopdf

Download the wkhtmltopdf binaries from the official website and install them on your system.

  1. Add wkhtmltopdf to your PATH

Add the wkhtmltopdf binary to your system PATH so that Selenium can find it.

  1. Use the save_as_pdf function

The save_as_pdf function takes a Selenium webdriver instance and a filename as arguments and saves the current page as a PDF.

def save_as_pdf(driver, filename): driver.execute_script('window.print();') sleep(5) with open(filename, 'wb') as file: file.write(driver.page_source.encode('utf-8'))

I was able to solve this problem using the pyautogui library. Although I think that this is not the best solution

import pyautogui as pag

driver.execute_script('window.print();')
time.sleep(20)
pag.typewrite('test.pdf')
time.sleep(1)
pag.press("enter")
time.sleep(20)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM