Invoke Firefox browser in headless mode using Selenium 4 and Python

Versions used while doing this blog post, (These are the prerequisites to automate firefox browser. Browser and driver versions should match)
selenium python version – 4.5.0
firefox browser version – 105
gecko driver version – 0.31.0 (Download link : https://github.com/mozilla/geckodriver/releases) [download this to a path in project directory]

Opening firefox in headless mode fastens the execution. This mode is really helpful for distributed executions.

Headless firefox browser can be opened using selenium by following below steps:

1. Instantiate an object with Options() class and set argument to start the browser in headless mode. We have set an argument to ‘headless’

options = Options()
options.headless = True

2. Instantiate (creation of object) driver object with webdriver.Firefox() (This step opens the firefox browser)

driver = webdriver.Firefox(options=options, executable_path='geckodriver path to be passed')

3. Now, next steps of maximizing the browser, setting implicit timeout for driver object and launch of expected website can be carried out

driver.implicitly_wait(10)
driver.maximize_window()
driver.get("https://www.google.com")

4. Quit/close the driver object after automating the necessary flows within the website.

driver.quit()

Sample code for reference

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True

driver = webdriver.Firefox(options=options, executable_path='geckodriver path to be passed')
driver.implicitly_wait(10)
driver.maximize_window()
driver.get("https://www.google.com")

driver.quit()

Leave a Reply

Your email address will not be published. Required fields are marked *