Automating web browsers with Selenium

24 09 2007

I have a new fun toy to play with: Selenium makes it possible for you to automate web tasks. After you start the Selenium server (a java command line program) you can get access to the browsers you have installed (Firefox, MSIE, Opera, Konqueror, you name it) and use the Selenium API to simulate user interaction with the browser in your favorite programming language (Java, Perl, PHP, Python, Ruby or C#). You can even use a Firefox extension to record your actions to rapidly develop these test cases.

To use Selenium via PHP under Gentoo Linux, download their Remote Control application and emerge dev-php/PEAR-Testing_Selenium and you’re good to go – here is something that I programmed to automatically upload pictures to Album.de via Firefox, otherwise I’d have to do it manually one-by-one by myself:

<?php

  // load API
  require_once 'Testing/Selenium.php';

  // "chrome" can use file upload dialogs, "firefox" can not
  $selenium = new Testing_Selenium("*chrome", "http://www.album.de/");
  $result = $selenium->start();

  // login to album.de
  $selenium->open("http://www.album.de/");
  $selenium->click("link=MEIN ALBUM");
  $selenium->waitForPageToLoad("30000");
  $selenium->type("email", "___YOUR_ACCOUNT_INFO___");
  $selenium->type("accountpass", "___YOUR_ACCOUNT_PASS___");
  $selenium->click("//td[2]/input");
  $selenium->waitForPageToLoad("30000");
  $selenium->click("link=Bilder hochladen");
  $selenium->waitForPageToLoad("30000");
  $selenium->select("albumID", "label=___YOUR_ALBUM_NAME___");
  $selenium->waitForPageToLoad("30000");

  // upload images
  foreach (glob("___YOUR_IMAGE_FOLDER___/*.jpg") as $image) {
    $selenium->type("upl_image", $image);
    $selenium->click("act_images_upload");
    $selenium->waitForPageToLoad("90000");
  }

  // logout, close browser
  $selenium->click("link=AUSLOGGEN");
  $selenium->waitForPageToLoad("30000");
  $selenium->close();
  $selenium->stop();

?>

All you need to do is start the remote control server:~/selenium-remote-control-0.9.2-SNAPSHOT/selenium-server-0.9.2-SNAPSHOT $ java -jar selenium-server.jarand then run the script via php upload.php
You need to enable URLs for fopen in your php.ini though: allow_url_fopen = On

But there is more than browser automation: You can use it in unit tests and thus help you in web development. Somebody even proposed to take screenshots with it, so you can create your own Browsershots application. In any case, a very nice tool.


Actions

Information

Leave a comment