Selenium Chrome save as pdf change download folder

后端 未结 3 1851
天涯浪人
天涯浪人 2021-02-06 17:04

I want to download a website as pdf file, it\'s working fine, but it should download the file to a specific path, instead it\'s just downloading the file to my default download

3条回答
  •  余生分开走
    2021-02-06 17:28

    The download.default_directory setting is only for downloaded content. Chrome treats files saved on the page differently. To change the default folder for a printout of the page, simply set the savefile.default_directory value instead.

    So the full example to print to pdf for a custom location:

    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),
               'savefile.default_directory': 'path/to/dir/'}
    
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_experimental_option('prefs', profile)
    chrome_options.add_argument('--kiosk-printing')
    
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(url)
    driver.execute_script('window.print();')
    

提交回复
热议问题