【问题标题】:How to find an element by matching exact text of the element in Capybara如何通过匹配 Capybara 中元素的确切文本来查找元素
【发布时间】:2012-12-02 11:17:12
【问题描述】:

我在 HTML 中有以下两个元素

<a href="/berlin" >Berlin</a>
<a href="/berlin" >Berlin Germany </a>

我正在尝试使用以下 Capybara 方法查找元素

find("a", :text => "berlin")

上面将返回两个元素,因为它们都包含文本柏林。

有没有办法匹配 Capybara 中的精确文本?

【问题讨论】:

  • 水豚还是 nokogiri?为什么这两个都被标记了?

标签: ruby regex capybara


【解决方案1】:

你也可以这样做:

find('a', text: 'Berlin', exact_text: true)

这将为 CSS 找到。

并且仅使用exact: true 而不是exact_text 将向您显示exact 选项仅对XPATH 有效的消息。

【讨论】:

  • 或者更多,可以使用find("a", exact_text: "berlin")
【解决方案2】:

我的偏好是将have_selectortextexact_text: true 一起使用:

expect(body).to have_selector 'a', text: 'Berlin', exact_text: true

【讨论】:

    【解决方案3】:

    要在 capybara 中使用 click_link,您需要在使用它的方法中再添加一个属性。

    click_link(link_name, :text => link_name)
    

    这里的 link_name 是链接的文本值。 使用 :text 关键字,我们指定我们要单击具有与我们的要求完全匹配的文本值的链接。

    【讨论】:

      【解决方案4】:

      取决于您使用的 gem 的版本

      find('a', text: 'Berlin', exact: true)
      

      可能会被弃用。在这种情况下,您将不得不使用

      find('a', text: 'Berlin', match: :prefer_exact)
      

      【讨论】:

        【解决方案5】:

        只需使用Capybara's exact option:

        Capybara.exact = true
        

        【讨论】:

          【解决方案6】:

          使用正则表达式而不是字符串作为:text 键的值:

          find("a", :text => /\ABerlin\z/)
          

          查看Method: Capybara::Node::Finders#all documentation 的“选项哈希”部分。

          PS:文本匹配区分大小写。您的示例代码实际上引发了一个错误:

          find("a", :text => "berlin")
          # => Capybara::ElementNotFound:
          #    Unable to find css "a" with text "berlin"
          

          【讨论】:

          • 这是最好的答案,这太糟糕了。 :哭:
          • 为什么我们在柏林之间有\A和\z?
          • 如何在正则表达式中添加占位符
          • 这可以通过写click_link(link_text, :text =&gt; link_text)来处理
          • This better-seeming answer 为我工作。
          猜你喜欢
          • 2020-08-24
          • 1970-01-01
          • 2021-01-18
          • 1970-01-01
          • 2019-10-07
          • 2018-12-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多