Tweak selenium python download name

0

I'm downloading a pdf through the automatic navigation through the site, so I deactivated the pdf preview of chrome and activated to download the pdf automatically, how would I change the name of this pdf file by code? There are 64 files, I thought of playing a variable with nothing, and giving a specific name for each of the 64, would it have?

First section of Còdigo is to disable the pdf viewer and to download automatically and the second is the button that I click to download

chrome_options = Options()
    download_dir = "C:\scrapy"
    chrome_options.add_experimental_option('prefs', {
        "plugins.plugins_list": [{"enabled":False,"name":"Chrome PDF Viewer"}],
        "download": {
        "prompt_for_download": False,
        "default_directory"  : download_dir
        }
    })

conta_completa = driver.find_element_by_id('btnVerContaCompleta')
    conta_completa.click()
    sleep(20)
    
asked by anonymous 22.10.2018 / 21:58

1 answer

0

No, this is not possible. What you can do is create a temporary folder, using tempfile.mkdtemp() and pass it to your default_directory ... So the browser will save the files in it. Then you move the file to another folder with the name you want by python using shutil.move() ...

Another thing you can not do is know when the download is finished. In the case of chrome, with this separate folder hint for download, you can do this by checking for partial download files in the folder.

chrome_options = Options()
download_dir = tempfile.mkdtemp()
try:
    chrome_options.add_experimental_option('prefs', {
        "plugins.plugins_list": [{"enabled":False,"name":"Chrome PDF Viewer"}],
        "download": {
        "prompt_for_download": False,
        "default_directory"  : download_dir
        }
    })
    #...
    conta_completa = driver.find_element_by_id('btnVerContaCompleta')
    conta_completa.click()
    sleep(5)  # espera o download começar
    while glob.iglob(os.path.join(download_dir, '*.crdownload')): 
        sleep(1)  # espera o download terminar
    # pega o 1o pdf que tiver, só terá 1 pois a pasta estava vazia antes:
    arquivo = glob.iglob(os.path.join(download_dir, '*.pdf'))[0] 
    shutil.move(arquivo, r'C:\scrapy\resultado.pdf')
finally:
    shutil.rmtree(download_dir) # remove todos os arquivos temporários
    
22.10.2018 / 22:32