Selenium is one of my favourite tool for automation.

In this post, I will demonstrate some basic code to download a file from a website in a headless mode , and also provide a docker file to make things simpler.

Python Code

Here is some basic code which will make an attempt to download a **7zip exe. **

from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected\_conditions as EC
from selenium.webdriver.common.by import By
import os
import time

print("******************************** STARTING ********************************")

display = Display(visible=0, size=(1024, 768))
display.start()

# To prevent download dialog
profile = webdriver.FirefoxProfile()
profile.set\_preference('browser.download.folderList', 2) # custom location
profile.set\_preference('browser.download.manager.showWhenStarting', False)
profile.set\_preference('browser.download.dir', '/srv/download')
profile.set\_preference("browser.download.manager.alertOnEXEOpen", False)
profile.set\_preference("browser.download.manager.closeWhenDone", False)
profile.set\_preference("browser.download.manager.focusWhenStarting", False)
#application/octet-stream,application/vnd.ms-excel 
profile.set\_preference('browser.helperApps.neverAsk.saveToDisk', 'application/x-msdownload,application/octet-stream')
try:
    browser = webdriver.Firefox(profile)
    browser.get('https://www.7-zip.org/')
    download\_button = WebDriverWait(browser, 20).until(EC.element\_to\_be\_clickable((By.CSS\_SELECTOR, 'td.Item a')))
    download\_button.click()
    print("clicked...")
    time.sleep(10    print (os.listdir("/srv/download"))
except Exception as ex:
    print(ex)
 
browser.close()
display.stop()


print("******************************** FINITO ********************************")

The code is fairly simple , we need