I am reading two questions here. Firstly, short, light.
Q: Now that I have found el , how do I access its HTML class attribute?
A: Use el.attribute('class') or its short arm el['class'] . See Selenium :: WebDriver :: Element.attribute .
Now longer.
Q: How can I check that an element marked with an el is marked as a favorite?
A: See below.
To give a better answer, I will need additional information about the composition of the page that we are testing. I made some basic assumptions:
- There are one or more
li elements on the page with the class 'resultItem' , some of which also have the class 'isFavorite' . - Each of these
li elements has one or more child elements, one of which is guaranteed to be a div with the class 'name' . - Only one such child
div will have the text 'f,f' .
Generally speaking, we have two ways to do this.
- We can find the corresponding
div , and then check that its parent li has the class 'isFavorite' . - We can find all
li elements with the class 'isFavorite' and then check that one of them contains the corresponding div .
There are many things we need to know here.
For Selenium, XPath selectors can be found by text, but are poorly suited for searching by class . CSS selectors are good for searching by class, but cannot find by text . None of them are perfect for finding the div we are after.
As mentioned above, we can get the class (attribute) of an element using element['class'] . As we found out, element.class calls Object#class , giving us Selenium::WebDriver::Element . el['class'] , in this case, gives the string 'name' . If its parent is called, we get 'resultItem isFavorite' .
We can get the text of an element using element.text . el.text would give us 'f,f' in this case. Like the JavaScript textContent function , it returns the text of the element and all its descendants, so calling text() on the parent element will also give us 'f,f' . Note that this method can be slow and returns an empty string if the item is not displayed in some way. Use with caution. See Selenium :: WebDriver :: Element.text for more details.
Given the above, let's see how methods # 1 and # 2 work. (Below is Ruby 1.9.3.)
Method # 1
div_elements = @driver.find_elements(:css, 'li > div.name').select { |e| e.text == 'f,f' } div_element = div_elements.first parent_li = div_element.find_element(:xpath, './..') parent_li_classes = parent_li['class'].scan(/\S+/) if parent_li_classes.include?('isFavorite')
Method # 2
favorite_items = @driver.find_elements(:css, 'li.isFavorite') if favorite_items.any? { |item| item.find_element(:css, 'div.name').text == 'f,f' }
Method No. 2, refactoring
if @driver.find_elements(:css, 'li.isFavorite').any? { |item| item.text == 'f,f' }