2013-06-25 43 views
5

我們使用watir進行測試並想知道如何選擇符合特定條件的一組divs?在我們的例子中(簡體)HTML看起來像這樣:在Watir中循環收集一個div

<div class="month_main> 
<div class="month_cell"> 
    some divs 
</div> 
<div class="month_cell"> 
    some_other_divs 
</div> 
<div class = "month_cell OverridenDay"> 
    <div id = "month-2013-05-04"/> 
</div> 
</div> 

我們想通過所有div環路以ID開始與被包含在也有OverridenDaymonth_cell父div的「月」。有沒有一個Xpath或正則表達式,我們可以與Watir瀏覽器類一起使用來做到這一點?

回答

10

一般

您可以用類似的方式獲得元素的集合,以得到一個單一的元素。你基本上需要複數元素類型的方法。例如:

#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" 
+0

非常感謝這一點,很很有幫助。 – larryq