Using Selenium with Python in Chrome to click "download" button and download PDF

Viewed 1105

I am trying to download a PDF from the following url,https://sec.report/Document/0001670254-20-001152/

There is a download button embedded in the html. I am using the following code to click the button and send the download to my desktop as defined in my path. The program runs without any errors but the PDF does not show up in the desktop. I have tried changing the location to different places, ie Downloads. I have also toggled the preferences in google chrome to download PDF files instead of automatically opening them in Chrome. Any ideas?

from selenium import webdriver

download_dir = "C:\\Users\\andrewlittle\\Desktop" 
options = webdriver.ChromeOptions()

profile = {"plugins.plugins_list": [{"enabled": False, "name": "Chrome PDF Viewer"}], 
               "download.default_directory": download_dir , "download.extensions_to_open": "applications/pdf"}
options.add_experimental_option("prefs", profile)
chromedriver_path = os.getcwd() + '/chromedriver'
driver = webdriver.Chrome(ChromeDriverManager().install())

driver.get('https://sec.report/Document/0001670254-20-001152/document_1.pdf')

driver.close()

Thanks in advance!

1 Answers

See the answer below:

import time
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium import webdriver

download_dir = "/Users/test/Documents/"

options = Options()
options.add_experimental_option('prefs',  {
    "download.default_directory": download_dir,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "plugins.always_open_pdf_externally": True
    }
)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)

driver.get('https://sec.report/Document/0001670254-20-001152/document_1.pdf')
time.sleep(3)
driver.quit()

I put the time.sleep in for some security in case the file takes a little longer to download. However, it is not necessary.

I also used the newer, Service and Options objects for Selenium.

The key to the code is the use of,

    "download.default_directory": download_dir,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "plugins.always_open_pdf_externally": True

These allow for Chrome to download the PDF without prompt to the directory of your choice.

Related