Headless Selenium testing with PhantomJS

As you know, Selenium is a marvelous library for automating a browser. It can be combined with Test::More and PhantomJS to provide a headless test suite.

An example script looks like:


#!/opt/perl

use Selenium::Remote::Driver;
use Selenium::Remote::WDKeys;

use Test::More;
use MIME::Base64;

my $driver = Selenium::Remote::Driver->new();

$driver->set_implicit_wait_timeout(3000);

$driver->get('http://www.google.com');
like($driver->get_title(), qr/^Google$/, "Arrived at Google homepage");

my $elem = $driver->find_element("input[name=q]", "css");
$elem->send_keys("Mojolicious");

open(my $fh,'>','mojoText.png');
binmode($fh);
my $png_base64 = $driver->screenshot();
print($fh MIME::Base64::decode_base64($png_base64));
close($fh);

$elem->send_keys(KEYS->{'enter'});

$elem = $driver->find_element("#resultStats", "css");
like($elem->get_text(), qr/About.*results/, "Got some results");

open($fh,'>','mojoResults.png');
binmode($fh);
my $png_base64 = $driver->screenshot();
print($fh MIME::Base64::decode_base64($png_base64));
close($fh);

$driver->quit();

done_testing();

This works under the assumption that PhantomJS is running like so:

[bpm@s001] c:~>./phantomjs --webdriver=4444
PhantomJS is launching GhostDriver...
Ghost Driver running on port 4444

The output looks like:

[bpm@s001] c:~/playground>/opt/perl google.pl 
ok 1 - Arrived at Google homepage
ok 2 - Got some results
1..2
[bpm@s001] c:~/playground>

2 Comments

I have a question about using Selenium in perl,
Does it have all the functionality that Java provide?

http://ns-id.com

Leave a comment

About Brian Medley

user-pic I blog about Perl.