Save pdf opened in browser using Selenium

Viewed 1462

So I'm logging into a web-app owned by my company and running a request to generate a pdf, this is all being done in python using the Internet Explorer Driver. I can only use IE because the company system does not work with any other browser.

Once I submit the request, a new IE window pops up with the pdf file I requested. I would like to save the pdf file to my computer. I realize its not easy to work with downloads in IE but there has to be a way to do it. I am also okay with save it as a png or any other format but the pdf is long (spans 2-5 pages typically) so a print screen or screenshot will not work.

Any suggestions on what I can do?

Below is a simple snippet of the code:

driver.implicitly_wait(5)

driver.find_element_by_name("invNumSrchTxt_H").send_keys("ABCDE")  #sending the parameters I need
driver.find_element_by_name("invDt_B").clear()  # Clearing out some preset params
driver.find_element_by_name("invDt_A").clear()


 # This is where I click the button and this pops open a new IE window with my pdf file in it.
 s=driver.find_element_by_name("Print_Invoice")
 s.click()
1 Answers

You can send directly a request using requests, since IE doesn't support settings configuration, and you should handle a popup.

A possible implementation could be:

import requests


def download_pdf_file(url, filename=None, download_dir=None):
    """
    Download pdf file in url,
    save it in download_dir as filename.
    """
    if download_dir is None: # set default download directory
        download_dir = r'C:\Users\{}\Downloads'.format(os.getlogin())

    if filename is None: # set default filename available
        index = 1
        while os.path.isfile(os.path.join(download_dir, f'pdf_{index}')):
            index += 1
        filename = os.path.join(download_dir, f'pdf_{index}')

    response = requests.get(url) # get pdf data
    with open(os.path.join(download_dir, filename), 'wb') as pdf_file:
        pdf_file.write(response.content) # save it in new file


driver.implicitly_wait(5)

driver.find_element_by_name("invNumSrchTxt_H").send_keys("ABCDE")  #sending the parameters I need
driver.find_element_by_name("invDt_B").clear()  # Clearing out some preset params
driver.find_element_by_name("invDt_A").clear()


# This is where I click the button and this pops open a new IE window with my pdf file in it.
s=driver.find_element_by_name("Print_Invoice")
s.click()

driver.download_pdf_file = download_pdf_file

driver.download_pdf_file(driver.current_url, # pdf url of the new tab
                  filename='myfile.pdf', # custom filename
                  download_dir='') # relative path to local directory
Related