Selenium, Webdriver and Headless Chrome

Oct 14,2017 at 12:58 pm By Ben Hutton

For anyone wanting an alternative to PhantomJS for Headless Selenium/Webdriver tests, you may want to have a look into Google’s new Headless Chrome.

Recently I was writing functional integration tests (I use this loosely) for validating deployment scripts.  Previously I had been using PhantomJS however this time I was having issues getting it working.   This is when I discovered the shaky nature of PhantomJS’s future.

After a bit of research I discovered that Google had recently release a headless version of Chrome.  At the time I was writing the tests it was so new that you had to either use the dev release of Chrome, or use Canary Chrome.

The below Python script uses the new Headless Chrome to load this website and assert the site title.  To get this working simply replace “path/to/chrome/binary” with the absolute path of your chrome binary.  In the case of my MacBook I have been using “/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary”.

Simple Python script to get you started

import warnings
import unittest

from selenium import webdriver

class FunctionalTests(unittest.TestCase):

    def setUp(self):
        warnings.filterwarnings("ignore", category=ResourceWarning)
        options = webdriver.ChromeOptions()
        options.binary_location = 'path/to/chrome/binary'
        options.add_argument('headless')
        options.add_argument('window-size=1200x600, chrome.verbose=true')
        self.browser = webdriver.Chrome(chrome_options=options)
        self.browser.implicitly_wait(10)

    def test_load_site(self):
        self.browser.get('https://benhutton.com.au')
        self.browser.get_screenshot_as_file('file.png')
        assert 'Adventures in Development' in self.browser.title


if __name__ == '__main__':
    unittest.main()

 

Screenshots

My favourite feature of headless chrome is the get_screenshot_as_file method.  This saves a screenshot of the browser window.  Very handy for debugging failed tests.  In the case of the above script it returned the below file when run.

 

Headless Chrome Screenshot
Headless Chrome Screenshot

 

Whether or not PhantomJS continues this at least provides an alternative for doing headless functional tests.  So far this has proved quite reliable.

Leave a comment

Login to Comment

Copyright © 2017 | Ben Hutton