一般
您可以用類似的方式獲得元素的集合,以得到一個單一的元素。你基本上需要複數元素類型的方法。例如:
#Singular method returns first matching div
browser.div
#Pluralized method returns all matching divs
browser.divs
集合可以使用與單個元素相同的定位符。
解決方案
對於你的問題,你可以這樣做:
#Iterate over divs that have the class 'month_cell OverridenDay'
browser.divs(:class => 'month_cell OverridenDay').each do |overridden_div|
#Within each div with class 'month_cell OverridenDay',
# iterate over any children divs where the id starts with month
overridden_div.divs(:id => /^month/).each do |div|
#Do something with the div that has id starting with month
puts div.id
end
end
#=> "month-2013-05-0"
如果你需要創建一個單一的集合,包括所有匹配的div的,你需要使用一個CSS或xpath選擇器。
使用CSS選擇器(注意,在的Watir-webdriver的,只有要素方法支持CSS-定位器):
divs = browser.elements(:css => 'div.month_cell.OverridenDay div[id^=month]')
divs.each do |e|
puts e.id
end
#=> "month-2013-05-0"
使用XPath:
divs = browser.divs(:xpath => '//div[@class="month_cell OverridenDay"]//div[starts-with(@id, "month")]')
divs.each do |e|
puts e.id
end
#=> "month-2013-05-0"
非常感謝這一點,很很有幫助。 – larryq