简体   繁体   English

Watir-webdriver:使用索引访问元素

[英]Watir-webdriver : Accessing elements using Indexing

I am trying to access a li element using indexing 我正在尝试使用索引访问li元素

<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: 对“ views-row”参数进行部分匹配:

@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: 如果您愿意,也可以盲目浏览div包含的li:

   @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. 根据Watir Wiki,Watir 支持 li元素上的:index方法。 So unless it is a bug in watir-webdriver, I think the index should work. 因此,除非它是watir-webdriver中的错误,否则我认为索引应该可以工作。

You may want to try the watir mailing list to see if this is a problem for others. 您可能想尝试一下watir邮件列表,以查看这是否对其他人有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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