I have a script that uses Selenium Python to download a PDF page made based on this question
My goal at the moment is to change the name of this file so that it is located with the name I chose and then change the destination folder of the saved file.
My doubts are: Where should I change so that the file is saved with the name I choose?
Even with the changes made to the “prefs=” variable, the file continues to be saved in the default chrome directory.
At the moment I have the following code:
JavaScript
x
39
39
1
chrome_options = webdriver.ChromeOptions()
2
chrome_options.add_argument('--headless') # Escondendo o navegador
3
driver = webdriver.Chrome(options=chrome_options)
4
driver.maximize_window()
5
settings = {
6
"recentDestinations": [{
7
"id": "Save as PDF",
8
"origin": "local",
9
"account": "",
10
}],
11
"isLandscapeEnabled": True,
12
"selectedDestinationId": "Save as PDF",
13
"version": 2,
14
}
15
16
prefs = {
17
"printing.print_preview_sticky_settings.appState": json.dumps(settings),
18
"profile.default_content_settings.popups" : 0,
19
20
"download.name":"name_file", # ?????? ESTE CÓDIGO NÃO ALTERA O NOME
21
22
"download.default_directory": r'C:Usersdiretorio_escolhido\' # ESTE CÓDIGO NÃO ALTERA O DESTINO,
23
24
"download.prompt_for_download": False,
25
"download.directory_upgrade": True,
26
"safebrowsing.enabled": True
27
}
28
29
30
chrome_options.add_experimental_option('prefs', prefs)
31
chrome_options.add_argument('--kiosk-printing')
32
33
driver = webdriver.Chrome(chrome_options=chrome_options)
34
driver.get(name_Object.url)
35
sleep(5) # Pausa para carregar os dados
36
driver.execute_script('window.print();')
37
38
print('Gerou o PDF')
39
Advertisement
Answer
Change download.default_directory
to savefile.default_directory
so your saving location works.
Sadly I think we can’t change the filename before download, but you can rename your file after download, by renaming the latest file in download folder:
JavaScript
1
6
1
import os
2
import shutil
3
download_folder = "C:\Users\username\Downloads\Test"
4
filename = max([download_folder + "\" + f for f in os.listdir(Initial_path)],key=os.path.getctime)
5
shutil.move(filename,os.path.join(Initial_path,r"newPDFName.pdf"))
6