Watir:如何检索与属性匹配的所有 HTML 元素?(类、ID、标题等)

tfr*_*ege 0 ruby testing each loops watir

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

<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>
Run Code Online (Sandbox Code Playgroud)

等等。

我需要对 Watir 做的是恢复带有 class="price" 的跨度内的所有文本,在此示例中:$ 180.00、$43.50 和 $51.85。

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

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

Jar*_*man 5

您可以使用复数方法来检索集合 - 使用spans而不是span

@browser.spans(:class => "price")
Run Code Online (Sandbox Code Playgroud)

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

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

puts texts
Run Code Online (Sandbox Code Playgroud)

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

texts = @browser.spans(:class => "price").map &:text
puts texts
Run Code Online (Sandbox Code Playgroud)