Watir:如何检索与属性匹配的所有HTML元素? (班级,身份,职称等)

时间:2013-06-13 21:26:23

标签: ruby loops testing watir each

我有一个动态创建的页面,并显示包含其价格的产品列表。由于它是动态的,因此重复使用相同的代码来创建每个产品的信息,因此它们共享标签和相同的类。例如:

<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>

等等。

我需要做的是使用Watir恢复所有跨越的内容,使用class =“price”,在这个例子中:$ 180.00,$ 43.50和$ 51.85。

我一直在玩这样的事情:     @browser.span(:class, 'price').each do |row|但无效。

我刚开始在Watir中使用循环。非常感谢您的帮助。谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用复数方法来检索集合 - 使用spans代替span

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

这会检索一个行为类似于Ruby数组的span collection对象,因此您可以像尝试一样使用Ruby #each,但我会使用#map代替这种情况:

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

puts texts

我会使用Symbol#to_proc技巧来进一步缩短代码:

texts = @browser.spans(:class => "price").map &:text
puts texts