Watir Webdriver计算UL列表中的项目数

Pau*_*les 9 watir watir-webdriver

我做了一些搜索,但我找不到合适的答案.基本上我有一个无序列表,可以有不同的长度.我想遍历列表,做一些其他的事情然后回来并选择列表中的下一个项目.当我定义循环应该迭代的次数时,我可以做到这一点,因为我知道列表中的项目数量.

但是我不想为每个测试定义这个,我想获取列表中的项目数,然后将其弹出到一个变量中,我可以用它来退出循环并执行下一个我想要的操作.

HTML就像这样:

<ul id="PageContent_cat">
  <li class="sel">
    <a target="_self" href="/searchlocation.aspx?c=S1">S1</a>
  </li>
  <li>
    <a target="_self" href="/searchlocation.aspx?c=S2">S2</a>
  </li>
  <li>
    <a target="_self" href="/searchlocation.aspx?c=S3">S3</a>
  </li>
  <li>
    <a target="_self" href="/searchlocation.aspx?c=S4">S4</a>
  </li>
  <li>
    <a target="_self" href="/searchlocation.aspx?c=S5">S5</a>
  </li>
  <li>
    <a target="_self" href="/searchlocation.aspx?c=S6">S6</a>
  </li>
  <li>
    <a target="_self" href="/searchlocation.aspx?c=S7">S7</a>
  </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

所以我可以看到列表中有7个项目.显然在watir我可以使用以下内容:

arr = ie.select_list(:name,'lr').getAllContents.to_a

但不是用webdriver.

我以为我可以使用'lis',但我只得到一个Hex结果:

$ bob = browser.ul(:id =>"PageContent_cat").lis put $ bob

谢谢,

保罗

ada*_*eed 11

根据您想要收集的信息以及您将要实现的目的,以下是通常的方式.而不是获得一个数字来定义你的迭代,然后迭代那么多次,你可以让它在到达最后一个元素时自然停止:

MyList = browser.ul(:id => "PageContent_cat")

#Scrape links from the UL for visiting
MyList.links.each do |link|
  puts link
  puts link.text
  b.goto(link)
  #etc
end

#Save li items to an array for later processing
MyArray = []

MyList.lis.each do |li|
  puts li.text
  MyArray << li.text
  #etc
end

#Iterate through your array in the same method, to report/visit/etc
MyArray.each do |item|
  puts "I collected something: #{item}"
  b.goto(item)
end #
Run Code Online (Sandbox Code Playgroud)

  • 你最好使用collect来收集li文本:MyList.lis.collect {| li | li.text}提供了一个数组 (4认同)