Friday, July 23, 2010

Moving on to the second example

The second example in the 5 minute getting started guide is an example for reading the suggestions from a suggestions list on google page. Type in any word there and voila it shows a list with suggestions on what you really "might be/are" seatching for.

This trick of pulling out that list is a neat webdriver trick.

The example it self is easy to convert to ruby, just copy the old one and remove the "puts driver.title" then add the new code. The ugly thing about it is that busy loop to wait for the suggestion list to appear, but we'll ignore that for now.

The ruby:fied code with added "catch all" exception handling to ensure that it closes the browser if possible. Note that you can replace firefox with e.g. ie or chrome if you like.

require "selenium-webdriver"

begin
  driver = Selenium::WebDriver.for :firefox
  driver.navigate.to "http://google.com"

  element = driver.find_element(:name, 'q')
  element.send_keys "cheese"

  # wait 5 s or until form is loaded
  five_sec = (Time.now) + 5
  until five_sec < Time.now
    resultsDiv = driver.find_element(:class_name, "gac_m")
    if resultsDiv.displayed?
      break
    end
  end

  #write em out
  list = driver.find_elements(:xpath, "//td[@class='gac_c']") 
  list.each do |ele|
    puts ele.text
  end

rescue
  puts $!, $@
end

driver.quit

The trick here was to find the ruby bindings equivalent for driver.findElement(By.className("gac_m")), driver.findElements(By.xpath("//td[@class='gac_c']")) and getText(). Quick search of the excellent (but devoid of examples) API documentation for the Ruby bindings turned out the correct answer. The answer was to use driver.find_element(:class_name, "gac_m"), driver.find_elements(:xpath, "//td[@class='gac_c']") and text.

When you run this it will reward you with a printout in the console with all the different suggestions for "cheese" weee! Cheesecake here we come!

Note that unless you are in Sweden you will get a different list then me, evil redirects ... :/

C:\Projects\selenium2_test>ruby googlesuggest_test.rb
cheesecake
cheesecake recept
cheese
cheesecake hallon
cheesecake fryst
cheesecake factory
cheesecake citron
cheesecake i glas
cheesecake passionsfrukt
cheesecake vit choklad


Next post will be about making it build server ready, we trolls love automation and will be adding Rspec, Rake and Ci_reporter stuff to this to get it to check if cheesecake is indeed one of the suggestions by Google.

p.s.
What frustrated me in the beginning was that the "meat" in the documentation is accessible thru the 3 boxes in the top right (class list, method list and file list). d.s.

1 comment:

  1. Thanks for this! I was having the same trouble with the lack of examples, and these really helped. Now to resume porting scripts...

    ReplyDelete