Selenium Chrome save as pdf change download folder

后端 未结 3 1850
天涯浪人
天涯浪人 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:32

    download.default_directory could be added not to appState but to "prefs" of add_experimental_option

    like:

    chrome_options.add_experimental_option("prefs", {
        'download.default_directory': 'C:\\Users\\Oli\\Google Drive',
        'download.directory_upgrade': True
    })
    

    but in your case it wouldn't help, as this option set location for 'file -> save as', and you need 'print -> save as'

    As a workaround you could use --print-to-pdf argument for Chrome (no need to run Chrome Webdriver, but Chrome itself in a headless mode)

    import os
    
    path_to_file = 'C:\\Users\\Oli\\Google Drive\\'
    name_of_file = '1.pdf'
    page_to_open = 'http://example.com'
    
    command_to_run = 'start chrome --headless --print-to-pdf="{0}{1}" {2}'.format(path_to_file, name_of_file, page_to_open)
    print('launch:'+command_to_run)
    
    os.popen(command_to_run)
    

    Be careful as it's running in silent mode, no warning messages if file is not created (for example if no such directory, or no admin rights to C:\Users, or no such webpage).

    And you could always test right in the command line (cmd) like:

    start chrome --headless --print-to-pdf="C:\\temp\\1.pdf" http://example.com
    

提交回复
热议问题