Watir: How to retrieve all HTML elements that match an attribute? (class, id, title, etc)

我与影子孤独终老i 提交于 2020-02-07 01:47:08

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/17097361/watir-how-to-retrieve-all-html-elements-that-match-an-attribute-class-id-ti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!