Automating web site interactions with Selenium

Dannon currently has a “promotion” called Cups of Hope where you can enter codes into their web page to donate money to breast cancer research. Entering data repeatedly gets old real fast, so I figured this would be a great example of using Selenium: it’s a practical example, yet simple enough to understand easily.

Selenium webdriver

I used Selenium webdriver to launch a Firefox window so I could see the progress visually. (Naturally the same end goal could be achieved using Mechanize, for example.) All that is needed for that is requiring the ‘selenium-webdriver’ gem.

Figuring out what to do

There were only a few basic steps to entering the information:

  1. Enter an email address into a specific field;
  2. Enter the code into another specific field;
  3. Click the submit button;
  4. Close the “thank you” popup;
  5. Start over with another code.

Setting field values

First, we need to get to the correct page (and wait for an animation to end before we start looking for the fields we need):


require "selenium-webdriver"

@driver = Selenium::WebDriver.for :firefox

@driver.navigate.to "http://cupsofhope.com/"
sleep(8) # wait for animation to finish

Then, we need a method to set field values:


def set_value(args)
element = @driver.find_element(:id, args.keys.first)
element.clear
element.send_keys args.values.first
end

All we do here is locate the desired HTML field via its ‘id’ attribute, clear it, and set its value. The clearing is necessary, because the filed values are kept after submission…

Once the field values have been set properly, we need to submit the form:


def submit_form
element = @driver.find_element(:id, 'cphContent_ContentPlaceHolder1_btnEnter')
element.click
end

This method is simple too: we simply select the form’s “submit” button and click it.

Now that we have these methods, registering a donation code is pretty easy:


def register_code(code)
set_value('cphContent_ContentPlaceHolder1_txtEmail' => 'email@example.com')
set_value('cphContent_ContentPlaceHolder1_txtCode' => code)
submit_form
end

[/ruby]

As you can see, the arguments  given to 'set_value' are simply a single-key hash with the form's HTML id as a key and the value we want to set.

And, we can tie it all together:



%W{DOMKXM LFRTYK}.each do |code|
register_code(code)

sleep(1) # wait for thank you popover to appear
element = @driver.find_element(:id, 'cboxClose')
element.click
end

@driver.quit

After registering each code, we close the "thank you" popup and start over with the next donation code.

You can download the entire source code form here.

This entry was posted in Automation, Ruby. Bookmark the permalink.