How to download all pdf files with selenium python?

SeleniumAutomation TestingTesting Tools

Answer − We can download all pdf files using Selenium webdriver in Python. A file is downloaded in the default path set in the Chrome browser. However, we can modify the path of the downloaded file programmatically in Selenium.

This is done with the help of the Options class. We have to create an object of this class and apply add_experimental_option. We have to pass the parameters - prefs and the path where the pdf is to be downloaded to this method. Finally, this information has to be sent to the webdriver object.

Syntax

op = Options()
p = {"download.default_directory": "../pdf"}
op.add_experimental_option("prefs", p)

Example

Code Implementation

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#Options instance
op = Options()
#configure path of downloaded pdf file
p = {"download.default_directory": "../pdf"}
op.add_experimental_option("prefs", p)
#send browser option to webdriver object
driver = webdriver.Chrome(executable_path='../drivers/chromedriver',
options=op)
#implicit wait
driver.implicitly_wait(0.8)
#url launch
driver.get("http://demo.automationtesting.in/FileDownload.html")
#browser maximize
driver.maximize_window()
#identify element
m = driver.find_element_by_id('pdfbox')
m.send_keys("infotest")
t = driver.find_element_by_id('createPdf')
t.click()
e = driver.find_element_by_id('pdf-link-to-download')
e.click()
#driver close
driver.close()
raja
Published on 29-Jun-2021 08:18:42
Advertisements