【问题标题】:How can I get some particular link form the links collection如何从链接集合中获取某些特定链接
【发布时间】:2013-08-14 12:33:37
【问题描述】:

我正在使用 watir-webdriver 有几行相同的代码如下所示:

...
    <p class="schedule-text">
    by 
    <a href="http://www.somesite.com">MarketingClub</a> 
    in 
    <a href="http://www.somesite2.com">Marketing</a>     
    </p>

我需要获取 p 标签中包含的第一个链接和 p 标签中包含的第二个链接 所以使用页面对象我添加了以下代码:

links(:followees_category, :css => "#home-followees li.animate-in ul li[data-show-id] p.schedule-text a")

...

followees_category_elements.attribute("href")

最后一行会给我两个链接:http://www.somesite2.com, http://www.somesite2.com 不幸的是,我无法在 css :last/:first 等中指明。

第二个链接可以通过将css更改为:

#home-followees li.animate-in ul li[data-show-id] p.schedule-text a + a

但是我怎样才能从这些块中获取第一个链接呢? 当然,我可以获得两个链接并使用每 2 个链接,但也许有替代解决方案?

【问题讨论】:

    标签: watir watir-webdriver pageobjects page-object-gem


    【解决方案1】:

    您可以使用 css nth-of-type 伪类根据元素的索引(或相对位置)获取元素。

    例如,a:nth-of-type(1) 可用于返回其父级第一行的所有链接:

    links(:followees_category, :css => "p.schedule-text a:nth-of-type(1)")
    

    对于第二个链接,您可以使用a:nth-of-type(2)。请注意,它是从 1 开始的索引。

    links(:followees_category, :css => "p.schedule-text a:nth-of-type(2)")
    

    第一个链接也可以a:first-of-type:

    links(:followees_category, :css => "p.schedule-text a:first-of-type")
    

    如果第二个链接总是最后一个链接,你也可以a:last-of-type:

    links(:followees_category, :css => "p.schedule-text a:last-of-type")
    

    【讨论】:

      【解决方案2】:

      我不建议使用这样的 css 选择器,因为它们会使您的测试更难阅读且更脆弱。

      但是,无论最终选择器是什么,我都会使用 Ruby 的 Enumerable 方法来获取第二个链接,如下所示:

      links.select.each_with_index {|_, i| i.odd? }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 1970-01-01
        • 2016-04-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多