简体   繁体   中英

File Not Saving While Downloading File in Headless chrome using Selenium in python

I am able to download file in normal chrome mode. where as, i am not able to see the download happening in headless chrome using selenium python.

I hope it is not saving the file downloaded

Tried with solutions provided by many users in internet but none of them works

options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
prefs = {'download.default_directory' :'/Users/nrpss/Downloads'}
options.add_experimental_option('prefs', prefs)

download_path = '/Users/nrpss/Downloads'

browser = webdriver.Chrome('chromedriver.exe', options=options)

browser.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')

params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_path}}

command_result = browser.execute("send_command", params)

print ("Headless Chrome Initiated")


### Below is ID for the Download link on webpage 

browser.find_element_by_id('downloadExportLink').click()

time.sleep(50)

def download_completed():
   for i in os.listdir('/Users/nrpss/Downloads'):
       if ".crdownload" in i:
           time.sleep(1)
 download_completed()

Expected result: File should be downloaded and saved in downloads folder.

Try adding download.prompt_for_download = False and download.directory_upgrade = True you car set safebrowsing_for_trusted_sources_enabled to False as well as safebrowsing.enabled .

try changing your prefs to:

prefs = {'download.default_directory' :'/Users/nrpss/Downloads',
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing_for_trusted_sources_enabled": False,
        "safebrowsing.enabled": False
         }

options.add_experimental_option('prefs', prefs)

Hope this helps you!

to enable headless downloads in Python:

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True 
driver = Chrome(options=options)
params = {'behavior': 'allow', 'downloadPath': '/path/for/download'}
driver.execute_cdp_cmd('Page.setDownloadBehavior', params)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM