【问题标题】:Finding a list of divs with a specific class in Watir在 Watir 中查找具有特定类的 div 列表
【发布时间】:2019-02-16 00:56:01
【问题描述】:

我们在页面上有 n 个具有相同类名的 div。

<div class="errors">
</div>
<div class="errors">
            Foo is invalid
</div>

我们要做的是检查是否有任何带有“错误”类的 div 显示“Foo 无效”的消息。

我们可以做到 @browser.div(:class=> '错误', :index => 2)

但这不包括消息在第一个或第 n 个 div 中的情况。

如果我们可以将所有匹配的 div 作为一个数组返回,将其展平,然后执行我们的断言,那就太好了。

或者也许返回匹配的 div 的数量,以便我们可以迭代它们。

我们在 Watir 1.9.2

【问题讨论】:

    标签: watir


    【解决方案1】:

    很容易陷入复杂的解决方案。首先从一般(甚至是低效的)步骤开始,然后在基本解决方案起作用后简化代码。这将在 Watir 1.9.2 中工作:

    @divs_with_error = []  #create a new array for the divs with class == "error"
    @divs_invalid = []     #create a new array for the divs with text == "Foo is invalid"
    
    browser.divs.each do |div|      #for each div on the page
      if div.class == "error"       #if the class == "error"
         @divs_with_error << div    #add it to our array
      end
    end
    
    @divs_with_error.each do |div|     #for each div in the @divs_with_error array
      if div.text == "Foo is invalid"  #if the text == "Foo is invalid"
        @divs_invalid << div           #add it to our next array
      end
    end
    

    如果这收集了您正在寻找的数据,您可以将其简化为一个块:

    @divs_with_error = []   #create a new array
    
    browser.divs.each do |div|
      if ((div.text == "Foo is invalid") && (div.class == "error"))
         @divs_with_error << div
      end
    end
    

    您可能需要使用 div.text.include?如果失败的 div 元素中有其他文本。您也可以使用收集!使用数组的方法来节省更多空间。与往常一样,您可以只收集某些属性,而不是收集整个 div 元素:

    @divs_with_error << [div.text, div.index]
    @divs_with_error << div.class
    

    希望有帮助!

    【讨论】:

    • 我提到过,我只是没有提供示例:D.
    【解决方案2】:

    如果您升级到 Watir 2.0 或使用 watir-webdriver gem,这将返回所有具有类 errors 和文本(准确)Foo is invalid 的 div(如果这是您想要做的):

    browser.divs(:class => "errors", :text => "Foo is invalid")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2013-09-01
      • 2018-08-05
      • 2014-08-06
      • 2016-06-13
      相关资源
      最近更新 更多