yannb
yannb

Reputation: 75

how do I retrieve list of element attributes using watir webdriver

I am trying to write a watir webdriver script which retrieves the attributes of an element and then gets their values. given element

  <input id="foobar" width="200" height="100" value="zoo" type="text"/>

hoping that I can do something like the following:

  testElement = $b.element(:id, "foobar")
  testElement.attributes.each do |attribute|
    puts("#{attribute}: #{testElement.attribute_value(attribute)}")
  end

I would hope to get

  id: foobar
  width: 200
  height: 100
  value: zoo
  type: text

Upvotes: 4

Views: 5848

Answers (3)

sameers
sameers

Reputation: 5095

The answer from @Željko-Filipin might be dated ... the document he links to, as of Aug '15, lists attribute_value as a method that extracts, well, the attribute value for a DOM element.

I have commonwatir-4.0.0, watir-webdriver-0.6.11, and Ruby 2.2.2 - the above method extracts the href of an a tag, for example.

Upvotes: 2

Justin Ko
Justin Ko

Reputation: 46836

I have seen people using javascript to get the list of attributes. The following shows how you could add a method to Watir::Element to get the list of attributes (though extending Watir is optional).

#Add the method to list attributes to all elements
require 'watir-webdriver'
module Watir
    class Element
        def list_attributes
            attributes = browser.execute_script(%Q[
                var s = [];
                var attrs = arguments[0].attributes;
                for (var l = 0; l < attrs.length; ++l) {
                    var a = attrs[l]; s.push(a.name + ': ' + a.value); 
                } ;
                return s;], 
                self )      
        end
    end
end

#Example usage
browser = Watir::Browser.new
browser.goto('your.page.com')
el = browser.text_field(:id, 'foobar')
puts el.list_attributes
#=> ["width: 200", "type: text", "height: 100", "value: zoo", "id: foobar"]

Upvotes: 5

Željko Filipin
Željko Filipin

Reputation: 57262

What are you trying to do?

As far as I can see Element class does not have #attributes method: http://watir.github.com/watir-webdriver/doc/Watir/Element.html

You can get element's HTML and parse it:

browser.element.html

Upvotes: 1

Related Questions