Watir:如何检索与属性匹配的所有HTML元素? (类,ID,标题等) [英] Watir: How to retrieve all HTML elements that match an attribute? (class, id, title, etc)

查看:72
本文介绍了Watir:如何检索与属性匹配的所有HTML元素? (类,ID,标题等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

以此类推。

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

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.

玩这样的事情:
@ browser.span(:class,'price')。每个| row | 都起作用,但是不起作用。

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

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

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

推荐答案

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

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

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

这将检索个跨度收藏集对象,其行为与Ruby数组类似,因此您可以像尝试使用Ruby #each 一样,但是我会使用 #map 代替这种情况:

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

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

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

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

这篇关于Watir:如何检索与属性匹配的所有HTML元素? (类,ID,标题等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆