I am using headless chrome to convert the webpage to pdf . So I am able to do it but I want to give specific name to the files downloaded (converted to pdf) as at a time I am converting 100+ pdf files using the url.Below is my code. I have tried shutil but the earlier files are deleted and only the latest file remains which I unable to open it.
import os
import time
import json
from selenium import webdriver
try:
import urlparse
from urllib import urlencode
except: # For Python 3
import urllib.parse as urlparse
from urllib.parse import urlencode
if os.path.exists(".DS_Store"):
os.remove(".DS_Store")
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'/Users/expether/Desktop/Diagence/Task 1' # Path where browser save files
new_path = r'/Users/expether/Desktop/Diagence/Task 1/mkpdf' # Path where to move file
photoid = 3
seaid_destination = 2
searchs = ["merge_recog","shape_recog","pattern_recog"]
for search in searchs:
url = "http://0.0.0.0:8080/" + search + "?"
params = {'photoid':photoid,'seaid_destination':seaid_destination}
file_name = search + str(photoid) + "_" + str(seaid_destination) + ".pdf"
url_parse = urlparse.urlparse(url)
query = url_parse.query #retrieve query item
url_dict = dict(urlparse.parse_qsl(query)) #convert the list to dict
url_dict.update(params) #add params to dict
url_new_query = urlencode(url_dict) #convert it in "percent-encoded"
url_parse = url_parse._replace(query=url_new_query) #replace old query with new query
new_url = urlparse.urlunparse(url_parse) #construct new url
print(new_url)
chrome_options = webdriver.ChromeOptions()
chrome_options.binary_location = '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'
chrome_options.add_experimental_option('prefs', profile)
chrome_options.add_argument('--kiosk-printing')
CHROMEDRIVER_PATH = '/Users/expether/Downloads/chromedriver'
driver = webdriver.Chrome(options=chrome_options, executable_path=CHROMEDRIVER_PATH)
driver.get(new_url)
import shutil
filename = max([download_path + "/" + f for f in os.listdir(download_path)],key=os.path.getctime)
shutil.move(filename,os.path.join(download_path,file_name))
# driver.execute_script('window.print();')
driver.quit()