I want to download a website as pdf file, it\'s working fine, but it should download the file to a specific path, instead it\'s just downloading the file to my default download
One more workaround. Just save the file as is and then move and rename it as needed.
Idea of the code below: check creation time of every (pdf) file in download directory, and compare with the time now. If the time delta less than some value (let's say 15 seconds), presumably this is the right file, move/rename the file where you need.
import os
import time
import json
from selenium import webdriver
appState = {
"recentDestinations": [
{
"id": "Save as PDF",
"origin": "local"
}
],
"selectedDestinationId": "Save as PDF",
"version": 2
}
profile = {'printing.print_preview_sticky_settings.appState': json.dumps(appState)}
download_path = r'C:\Users\Oli\Downloads' # Path where browser save files
new_path = r'C:\Users\Oli\Google Drive' # Path where to move file
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)
chrome_options.add_argument('--kiosk-printing')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('http://example.com/')
driver.execute_script('window.print();')
new_filename = 'new_name.pdf' # Set the name of file
timestamp_now = time.time() # time now
# Now go through the files in download directory
for (dirpath, dirnames, filenames) in os.walk(download_path):
for filename in filenames:
if filename.lower().endswith(('.pdf')):
full_path = os.path.join(download_path, filename)
timestamp_file = os.path.getmtime(full_path) # time of file creation
# if time delta is less than 15 seconds move this file
if (timestamp_now - timestamp_file) < 15:
full_new_path = os.path.join(new_path, new_filename)
os.rename(full_path, full_new_path)
print(full_path+' is moved to '+full_new_path)
Note: it's just an example. You need to think about all you actions. To make the code stable you might need to add some exceptions handling. Better to move this additional code to a function. And so on.