Can't download PDF with selenium webdriver + firefox Can't download PDF with selenium webdriver + firefox selenium selenium

Can't download PDF with selenium webdriver + firefox


I solved this problem by passing the selenium session to the Python requests library and then fetching the PDF from there. I have a longer writeup in this StackOverflow answer, but here's a quick example:

import requestsfrom selenium import webdriverpdf_url = "/url/to/some/file.pdf"# setup webdriver with options driver = webdriver.Firefox(..options)# do whatever you need to do to auth/login/click/etc.# navigate to the PDF URL in case the PDF link issues a # redirect because requests.session() does not persist cookiesdriver.get(pdf_url)# get the URL from Selenium current_pdf_url = driver.current_url# create a requests sessionsession = requests.session()# add Selenium's cookies to requestsselenium_cookies = driver.get_cookies()for cookie in selenium_cookies:    session.cookies.set(cookie["name"], cookie["value"])# Note: If headers are also important, you'll need to use # something like seleniumwire to get the headers from Selenium # Finally, re-send the request with requests.sessionpdf_response = session.get(current_pdf_url)# access the bytes response from the sessionpdf_bytes = pdf_response.content