Invoke Chrome browser in headless mode using Selenium 4 and Python

Versions used while doing this blog post, (These are the prerequisites to automate chrome browser. Browser and driver versions should match)
selenium python version – 4.5.0
chrome browser version – 105
chrome driver version – 105 (Download link : https://chromedriver.chromium.org/downloads) [download this to a path in project directory]

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

Headless chrome 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.Chrome() (This step opens the chrome browser)

driver = webdriver.Chrome(options=options, executable_path='chromedriver 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.chrome.options import Options

options = Options()
options.headless = True

driver = webdriver.Chrome(options=options, executable_path='chromedriver 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 *