Watir Webdriver counting number of items in a UL list
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 somet开发者_StackOverflow中文版hing 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
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 #
puts browser.ul(:id => "PageContent_cat").lis.length
精彩评论