Search code examples
rubycss-selectorsselenium-rchyperlink

Trouble with Selenium Client for Ruby and Xpath Selectors - multiple links from a single table


I'm porting over a few scripts from Watir to Selenium-RC to see how difficult the change may be for our organization.

I have a table with class 'global-list', that contains 4 columns, each column with an unordered list, and each list element containing a word with a hyperlink.

In Watir, I would simply use:

@browser.table(:class, /global-list/).links.each {|link| puts link.text,link.href}

With Selenium there doesn't appear to be such an easy way to do this. I want all of the links (href and text) from that single table. At first I thought my Xpath was incorrect because it would only show me the first column (of 4), or the first href element.

puts @browser.get_xpath_count("//table[@class='global-list']//a[@href]")
- gives me a result of 64 links (the total across all 4 tr's and/or ul's).

puts @browser.get_text("//table[@class='global-list']//a[@href]")
- gives me a single text result (just the first td in the first tr).

puts @browser.get_text("//ul[@class='global-list']")
- gives me the first column of text only (the first ul in the first tr).

I am new to Selenium, but I have read the documentation and available methods (http://selenium-client.rubyforge.org/) and do not yet see a straightforward solution.

I have also tried the DOM locator method, but if get_text or get_attribute are my only options, I'm not able to improve my results that way.


Solution

  • You're right, there is no single way to do that in Se. But you were most of the way.

    # get the number of links
    num_links = @browser.get_xpath_count("//table[@class='global-list']//a[@href]")
    # and now iterate over them
    for i in 1 .. num_links do
      puts @browser.get_text("//table[@class='global-list']//a[@href][" + i + "])
    end
    

    Notice the iterator as part of the xpath. Now, you could get even fancier and iterate over the number of columns and then the number of links which uses the same trick.

    Of course if you use 2.0a7 you can use CSS as provided by the Sizzle library which has alternate ways of referencing a specific item (though does not solve the get_xpath_count portion).