How to run a headless browser with Selenium Python

One day, I came across the word “headless browser” and it made no sense to me. I initially thought it was a fancy term for new web browser brand.

I WAS WRONG.

A headless browser is when a web browser is running without seeing it on the screen. It just runs in the background.

To enable this feature the browser options must be configured. In this case, Chrome and Firefox browsers will be used.

Before proceeding make sure that python, selenium, Chrome and Firefox browsers are installed.

Below is the code snippet on how to run a browser in headless mode.

from selenium import webdriver

'''Using Firefox Browser'''
options = webdriver.FirefoxOptions() # selenium 3.8.0 above
options.add_argument('-headless') # alternatively options.set_headless(headless=True)

driver = webdriver.Firefox(firefox_options=options)
driver.get('http://www.google.com')
print(driver.title)
driver.quit()


'''Using Chrome Browser'''
options = webdriver.ChromeOptions() # selenium 3.8.0 above
options.set_headless(headless=True)

driver = webdriver.Chrome(chrome_options=options)
driver.get('http://www.google.com')
print(driver.title)
driver.quit()

For more samples, kindly visit my GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s