Watir Webdriver counting number of items in a UL list

吃可爱长大的小学妹 提交于 2019-12-21 09:08:12

问题


I've done a few searches and I'm unable to find a suitable answer. Basically I have an unordered list which can be of a varying length. I want to iterate through the list, do some other things and then come back and select the next item on the list. I can do this fine when I define the amount of times my loop should iterate as I know the amount of items in the list.

However I don't want to define this for each test, I want to grab the number of items in the list and then pop that into a variable that I can use to exit the loop and do the next thing I want.

The HTML is like so:

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

So I can see there are 7 items in the list. Apparently in watir I could have used something the following:

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

But not with webdriver.

I thought I could maybe use 'lis' but I just get a Hex result:

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

Thanks,

Paul


回答1:


Depending on the information you're wanting to gather and what purpose you're going to put it to, here is the way that is typically done. Rather than getting a number to define your iterations and THEN iterating that number of times, you can have it stop naturally when it reaches the last element:

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 #



回答2:


puts browser.ul(:id => "PageContent_cat").lis.length



来源:https://stackoverflow.com/questions/7245702/watir-webdriver-counting-number-of-items-in-a-ul-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!