'Headless selenium chromium/chrome downloads dont's run/save
I'm using a script to download some PDF files to a folder on my computer. The script works perfectly, however, when this same script is run with the argument ("--headless") of chrome active, the files are no longer saved as usual.
I can't understand what this "headless" property is doing to prevent files from being saved.
Below is the code being used: (No error is displayed when running the script.)
######### looping if ctrl+p
print("Setando configurações...")
settings = {
"recentDestinations": [{
"id": "Save as PDF",
"origin": "local",
"account": "",
}],
"isLandscapeEnabled": True,
"selectedDestinationId": "Save as PDF",
"version": 2,
}
prefs = {
"printing.print_preview_sticky_settings.appState": json.dumps(settings),
"profile.default_content_settings.popups" : 0,
"savefile.default_directory": r'/home/file_name/directory_downloads/pdfs',# Para salvar com o 'headless' inativo
"download.default_directory": r'/home/file_name/directory_downloads/pdfs', # Para salvar com o 'headless' ativo
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')
chrome_options.add_argument('--headless') # Se ativo, salva os arquivos em um diretório desconhecido ou sobrepões arquivos salvos
print('Abrindo navegador...')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(dashObject.url)
driver.maximize_window()
print('Pausa para carregar o conteúdo da página')
sleep(7)
texto_xpath2 = driver.find_element_by_xpath('//*[@id="embedWrapperID"]/div[2]/logo-bar/div/div/div/logo-bar-navigation/span/a/span/span[3]').text
int_num_page2 = int(texto_navegacao_xpath2)
print('Preparando os arquivos PDFs...')
int_num_page = 1
while int_num_page <= int_num_page2:
numero_pagina1 = str(int_num_page)
driver.execute_script('window.print();')
print(f'PDF da pagina {int_num_page} de {int_num_page2} OK')
print('Proxima pagina...')
xpath_next = '//*[@id="embedWrapperID"]/div[2]/logo-bar/div/div/div/logo-bar-navigation/span/button[2]'
driver.find_element_by_xpath(xpath_next).click()
sleep(3)
print("Mudando nome do arquivo...")
pasta_download = pasta_pdfs + '/'
arquivo_pdf = max([pasta_download + f for f in os.listdir(pasta_download)],key=os.path.getctime)
shutil.move(arquivo_pdf,os.path.join(pasta_download,r"file_name"+ numero_pagina1 + dashUUID + ".pdf"))
int_num_page += 1
print('Fechando navegador...')
driver.quit()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
