Clipped on 2013-09-08 13:48:54 -0500
Running Headless Selenium with Chrome
Running a headless Selenium machine with Google’s Chrome installed provides a scalable way to automate your tests on one of the most popular browsers in use.
Here are step by step instructions for installing a headless Selenium server with Chrome and Vagrant.
Side note: Why use Selenium instead of PhantomJS?
- Get up and running quickly
- Run a sample script that demos it works
The code you write locally should work when deployed at scale in production. These tools help us do that by creating identical environments for development and production.
Both are free downloads. Install with the default settings
I also assume you can use a command line and have some vague idea of what a virtual machine and Vagrant is.
Create a “Vagrantfile”
This file tells Vagrant how configure the testing environment. It applies universally to both development and production.
Create a project directory and create a file named
The setup.sh file executes when Vagrant creates a virtual machine for you. In the same folder as you created your
Run “vagrant up”
On your command line and in the directory where you created the
VagrantFile, run the following command:
This will kick off downloading and installing all the pieces neccessary. It should look like this:
Make sure it’s running
You can check to see if everything is working by going to
VagrantFilehas been configured to forward port 4444 on your localhost. This allows you UI control of the Selenium browser. This page shows you all the sessions that you’re running in your virtual machine. If you see this page, everything is OK.
Install the selenium-webdriver
In order to write NodeJS scripts that talk to Chrome you will need the Selenium-Webdriver for NodeJS.
On your command line, install
selenium-webdriverwith the following command. This will install the modules needed for interacting with Selenium.
Write your first Selenium script
This first script will go to Google’s homepage, type in a query, then print out the HTML.
Run your test
Run your test with node. You should see the HTML that was rendered by the Chrome browser.
So now that you have this up and running what can you use it for?
Running your automated test suites: This is great for doing integration testing against Chrome browsers and probably responsive websites.
Testing your Chrome Extentions: Debugging Chrome Extensions can be a bit of a pain. This could be your Asprin.
Taking many screenshots: If you want to make screenshots of many pages at once.
Scraping stubborn websites: I wasn’t able to scrape a website using PhantomJS because it fired JSONP requests long after the onLoad() event fired. Simply waiting for the event loop to empty itself wansn’t enough. A combination of debugging with a real browser and Selenium, I was more successful at getting the DOM after the scripts had run.