【问题标题】:How to return all elements of same class in HTML in Watir如何在 Watir 的 HTML 中返回同一类的所有元素
【发布时间】:2020-01-15 03:24:42
【问题描述】:

我正在尝试返回具有相同类的 HTML 元素数组。我实际上看到了一些类似的问题,例如

How to get the number of elements having same attribute in HTML in Watir?

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

HTML 看起来像这样

<table class="module grid grid-50">
  <span bo-bind="row.date | sgDate">20/04/2018</span>
  <span bo-bind="row.date | sgDate">22/04/2018</span>
  <span bo-bind="row.date | sgDate">23/06/2018</span>
  <span bo-bind="row.date | sgDate">06/09/2018</span>
  <span bo-bind="row.date | sgDate">15/09/2018</span>
</table 

我试过了

content = browser.elements(:class =&gt; "module.grid.grid-50") puts content

返回&lt;Watir::HTMLElementCollection:0x00000000053fc460&gt;

我想输出这些日期的数组,而不是这条消息。 我想我在这里遗漏了一些东西,但不知道到底是什么。

我在 Rubydoc 上读到 ElementCollection 包含 to_a 方法,该方法将集合作为数组返回,我想知道是否也可以将它包含在这里。

【问题讨论】:

  • 您能否详细说明您想要实现或需要的目标?通常,您不需要将 HTMLElementCollection 转换为数组。 HTMLElementCollection 继承了所有 ElementCollection 方法,其中还包括 Enumerable。

标签: html ruby watir


【解决方案1】:

:class 定位器采用类列表而不是 CSS 选择器。寻找类“module.grid.grid-50”告诉Watir寻找如下元素:

<div class="module.grid.grid-50"> 

如果你想通过多个类进行匹配,你想传入一个单独的类的数组:

tbl = browser.table(class: ['module', 'grid', 'grid-50'])
tbl.spans(bo_bind: /row.date/).map(&:text)
#=> ["20/04/2018", "22/04/2018", "23/06/2018", "06/09/2018", "15/09/2018"]

【讨论】:

  • 非常感谢@JustinKo !!
  • @user12051965 如果他回答您的问题,请接受此回答。答案左侧有一个神圣的勾号,如果你点击它,它会变成绿色。答案的作者将获得 15 分的积分。
猜你喜欢
  • 2011-07-30
  • 1970-01-01
  • 2011-09-19
  • 2013-06-10
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
相关资源
最近更新 更多