简体   繁体   中英

Watir-webdriver : Accessing elements using Indexing

I am trying to access a li element using indexing

<div class="item-list">
<ul>
<li class="views-row views-row-1 views-row-odd views-row-first">
<li class="views-row views-row-2 views-row-even">
<li class="views-row views-row-3 views-row-odd">
<li class="views-row views-row-4 views-row-even">
<li class="views-row views-row-5 views-row-odd">
<li class="views-row views-row-6 views-row-even">
<li class="views-row views-row-7 views-row-odd">
<li class="views-row views-row-8 views-row-even">
<li class="views-row views-row-9 views-row-odd views-row-last">
</ul>
</div>

The code I am using is

@browser.div(:class,'item-list').ul.li(:index => 2)

The question is : These are elements on a page and I will be using a loop to access each element. I thought using indexing will solve the problem but when I write my code and execute it I get the following error

expected #<Watir::LI:0x2c555f80 located=false selector={:index=>2, :tag_name=>"li"}> to exist (RSpec::Expectations::ExpectationNotMetError)

How can I access these elements using Indexing.

If you've got class-naming that nice, forget indexing! Do a partial match on the "views-row" parameter:

@browser.li(:class => /views-row-1/)

This can easily be parameterized for looping (although I don't know what you're doing with the information so this loop will not be very exciting).

x = 0
until x==9
  x+=1
  puts  @browser.li(:class => /views-row-#{x}/).text
end

You could also blindly loop through the li's contained in your div if you'd like:

   @browser.div(:class,'item-list').lis.each do |li|
      puts li.text
   end

According to the Watir wiki, Watir supports the :index method on the li element. So unless it is a bug in watir-webdriver, I think the index should work.

You may want to try the watir mailing list to see if this is a problem for others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM