【问题标题】:Ruby - Watir gem to grab linksRuby - Watir gem 来获取链接
【发布时间】:2012-10-26 19:12:01
【问题描述】:

有什么方法可以获取给定属性的所有链接?

在树下,我得到了很多这样的标签:

<div class="name">
<a hef="http://www.example.com/link">This is a name</a>
</div>

有没有办法做这样的事情:b.links(:class, "name") 它会输出所有 div 名称类的所有超链接和标题?

【问题讨论】:

    标签: ruby watir ruby-1.9


    【解决方案1】:

    明确地描述了关于属性的浏览器对象,这就是你必须这样做的方式。否则,@SporkInventor 的答案就是链接属性。

    @myLinks = Array.new
    @browser.divs(:class => "name").each do |d|  
       d.links.each {|link| @myLinks << link }
    end
    
    1. 创建一个新数组来收集我们的链接。
    2. 对于浏览器中类等于“name”的每个 div,抓取所有链接并将它们放入数组中。

      @myLinks.each {|link| puts link.href } #etc 等

    【讨论】:

    • 实际上所有的解决方案都很棒。希望能给大家加分。非常感谢。
    【解决方案2】:

    在这种情况下,我会使用 CSS 选择器:

    #If you want all links anywhere within the div with class "name"
    browser.links(:css => 'div.name a')
    
    #If you want all links that are a direct child of the div with class "name"
    browser.links(:css => 'div.name > a')
    

    或者如果你更喜欢 xpath:

    #If you want all links anywhere within the div with class "name"
    browser.links(:xpath => '//div[@class="name"]//a')
    
    #If you want all links that are a direct child of the div with class "name"
    browser.links(:xpath => '//div[@class="name"]/a')
    

    示例(css)

    假设你有一个类似的 HTML:

    <div class="name">
        <a href="http://www.example.com/link1">
            This link is a direct child of the div
        </a>
    </div>
    <div class="stuff">
        <a href="http://www.example.com/link2">
            This link does not have the matching div
        </a>
    </div>
    <div class="name">
        <span>
            <a href="http://www.example.com/link3">
                This link is not a direct child of the div
            </a>
        </span>
    </div>
    

    然后css方法会给出结果:

    browser.links(:css, 'div.name a').collect(&:href)
    #=> ["http://www.example.com/link1", "http://www.example.com/link3"]
    
    browser.links(:css, 'div.name > a').collect(&:href)
    #=> ["http://www.example.com/link1"]
    

    【讨论】:

      【解决方案3】:

      我认为开箱即用的 watir 无法做到这一点。

      但是可以使用“waitr-webdriver”完全按照您的类型来完成。

      irb(main):001:0> require 'watir-webdriver'
      => true
      irb(main):002:0> b = Watir::Browser.new :firefox
      => #<Watir::Browser:0x59c0fcd6 url="about:blank" title="">
      irb(main):003:0> b.goto "http://www.stackoverflow.com"
      => "http://stackoverflow.com/"
      irb(main):004:0> b.links.length
      => 770
      irb(main):005:0> b.links(:class, 'question-hyperlink').length
      => 91
      

      【讨论】:

        猜你喜欢
        • 2019-05-21
        • 2017-08-05
        • 1970-01-01
        • 2010-12-29
        • 2012-09-17
        • 2017-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多