Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 489
Srknt73 Avatar asked May 03 '26 22:05

Srknt73


1 Answers

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!

like image 67
Moshe Slavin Avatar answered May 05 '26 12:05

Moshe Slavin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!