xpath - 循环遍历 Watir 中的一组 div

标签 xpath watir

我们正在使用 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>

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

最佳答案

一般

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

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

关于xpath - 循环遍历 Watir 中的一组 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17306534/

相关文章:

ruby-on-rails - Selenium /水 : 'InvalidCookieDomain' error when trying to add cookie

internet-explorer - 使用 Watir 测试不同版本的 IE

ruby - 不想关注 .goto

php - 获取不在属性X的节点内的html节点

Java:解析XML并将所有数据内容绑定(bind)到Map <K, V>

regex - 具有XPath正则表达式的字符串的小写部分

selenium - 从任意位置启动 Watir/Selenium Chrome 驱动程序二进制文件

xpath - 选择节点,其中包含具有特定属性的后代

javascript - 使用 selenium chromedriver 检查复选框

watir - `visible?` 和 `present?` 有什么区别?