问题
I have this HTMLcode:
<div class="A">
<div class="B">
Text1
</div>
</div>
<div class="A">
<div class="B">
Text2
</div>
</div>
So i need to find index of div class='A' where i find some text. I use Watir Webdriver and now i have this code:
if @ff.div(:class=>'A').div(:text=>'Text1')
then ind=@ff.div(:class=>'A').index
end
but of course this doesn't work saying 'undefined local variable or method `index''.
回答1:
There's no way to get the index using the webdriver since they are relative to the collection of matched elements. What you can try to do is collect the elemetns text as Array and then get the index of the target text.
@@ff.divs(:class, 'A').collect(&:text).index('Text1')
Note that this will only work for simple scenarios (like your example). If you need to attack a more complex case update your example to match the real scenario.
回答2:
If you are trying to get the index as a way to address the element you want to work with, and the best way to locate it is based on some attribute of a child element, then there is a better way.
e.g. if your objective was to click the instance of class A that was wrapped around the div class B with "Text1" in it, then do this
browser.div(:class => 'B', :text => 'Text1').parent.click
That's especially good for situations where the outer container you want has no useful attributes.
In your example above however, you may also simply be able to do this
browser.div(:class => 'A', :text => 'Text1').click
来源:https://stackoverflow.com/questions/8666822/how-to-get-index-of-parent-element-using-watir-webdriver