【问题标题】:looping through a collection of divs in Watir循环遍历 Watir 中的 div 集合
【发布时间】:2013-06-25 20:07:44
【问题描述】:

我们正在使用 watir 进行测试,想知道如何选择一组满足特定条件的 div?在我们的例子中,(简化的)html 看起来像这样:

<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>

我们希望遍历所有 id 以“月”开头的 div,这些 div 包含在 month_cell 父 div 中,这些 div 也有 OverridenDay 类。是否有可以与 Watir 浏览器类结合使用的 Xpath 或正则表达式来执行此操作?

【问题讨论】:

    标签: xpath watir


    【解决方案1】:

    常规

    您可以通过与获取单个元素类似的方式获取元素集合。您基本上需要复数元素类型方法。例如:

    #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-selector(注意在 watir-webdriver 中,只有 elements 方法支持 css-locators):

    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"
    

    【讨论】:

    • 非常感谢,非常有帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-06-16
    • 2016-07-16
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    相关资源
    最近更新 更多