0

I have a page that is dynamically created and displays a list of products with their prices. Since it's dynamic, the same code is reused to create each product's information, so they share the tags and same classes. For instance:

<div class="product">
  <div class="name">Product A</div>
   <div class="details">
    <span class="description">Description A goes here...</span>
    <span class="price">$ 180.00</span>
  </div>
 </div>

 <div class="product">
   <div class="name">Product B</div>
    <div class="details">
      <span class="description">Description B goes here...</span>
      <span class="price">$ 43.50</span>
   </div>
  </div>`

<div class="product">
 <div class="name">Product C</div>
  <div class="details">
    <span class="description">Description C goes here...</span>
    <span class="price">$ 51.85</span>
 </div>
</div>

And so on.

What I need to do with Watir is recover all the texts inside the spans with class="price", in this example: $ 180.00, $43.50 and $51.85.

I've been playing around with something like this: @browser.span(:class, 'price').each do |row| but is not working.

I'm just starting to use loops in Watir. Your help is appreciated. Thank you!

kgdesouz
  • 1,966
  • 3
  • 16
  • 21
tfrege
  • 91
  • 3
  • 9

1 Answers1

5

You can use pluralized methods for retrieving collections - use spans instead of span:

@browser.spans(:class => "price")

This retrieves a span collection object which behaves in similar to the Ruby arrays so you can use Ruby #each like you tried, but i would use #map instead for this situation:

texts = @browser.spans(:class => "price").map do |span|
  span.text
end

puts texts

I would use the Symbol#to_proc trick to shorten that code even more:

texts = @browser.spans(:class => "price").map &:text
puts texts
Jarmo Pertman
  • 1,905
  • 1
  • 12
  • 19