Change the download name Selenium python

Asked

Viewed 1,242 times

0

I am downloading a pdf through the automatic navigation through the site, for this I disabled the pdf view of Chrome and activated to download the pdf automatically, could I change the name of this file in pdf by the code? There are 64 files, I thought to play a variable with nothing, and to give a specific name to each of the 64, would like?

First snippet of Còdigo serves to disable the pdf viewer and automatically download and its second is the button 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)

1 answer

0

No, this is not possible. What you can do is create a temporary folder using tempfile.mkdtemp() and spend it on 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 using python shutil.move()...

Another thing that is not possible to do is know when the download is finished. In the case of Chrome, with this separate folder tip 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
  • helps this a lot, because creating 64 folders I play each one in the correct folder and do not need to change the name, despite leaving the code very long, so I ask, even after changing the folder has no way to change the name of the file?

  • What Selenium does is simulate user interaction, @Guilherme - it can only click on the link. You have set the browser not to ask for the name before saving..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.