Selenium ChromeDriver – How to Configure ChromeDriver for Headless Mode

browser-optionsgoogle-chrome-headlesspythonselenium-chromedriverselenium-webdriver

I'm working on a python script to web-scrape and have gone down the path of using Chromedriver as one of the packages. I would like this to operate in the background without any pop-up windows. I'm using the option 'headless' on chromedriver and it seems to do the job in terms of not showing the browser window, however, I still see the .exe file running. See the screenshot of what I'm talking about. Screenshot

This is the code I am using to initiate ChromeDriver:

options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"])
options.add_argument('headless')
options.add_argument('window-size=0x0')
chrome_driver_path = "C:\Python27\Scripts\chromedriver.exe"

Things I've tried to do is alter the window size in the options to 0x0 but I'm not sure that did anything as the .exe file still popped up.

Any ideas of how I can do this?

I am using Python 2.7 FYI

Best Answer

It should look like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')  # Last I checked this was necessary.
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)

This works for me using Python 3.6, I'm sure it'll work for 2.7 too.

Update 2018-10-26: These days you can just do this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)

Update 2023-05-22: Chrome’s Headless mode got an upgrade and now both headless and headful modes have been unified under the same implementation. See https://developer.chrome.com/articles/new-headless/

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless=new')
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)

To try the new Headless mode, pass the --headless=new command-line flag:

chrome --headless=new

For now, the old Headless mode is still available via:

chrome --headless=old

Currently, passing the --headless command line flag without an explicit value still activates the old Headless mode — but we plan to change this default to new Headless over time.

Related Question