2

属性を指定してすべてのリンクを取得する方法はありますか?

ツリーの下には、次のタグがたくさんあります。

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

このようなことを行う方法はありますか:b.links(:class, "name")すべての div 名クラスからすべてのハイパーリンクとタイトルを出力しますか?

4

3 に答える 3

2

属性に関してブラウザー オブジェクトをどのように記述したかを明示的に説明すると、これがその方法になります。それ以外の場合、@SporkInventorの回答はリンク属性に適しています。

@myLinks = Array.new
@browser.divs(:class => "name").each do |d|  
   d.links.each {|link| @myLinks << link }
end
  1. リンクを収集する新しい配列を作成します。
  2. 「name」に等しいクラスを持つブラウザーのすべての div について、すべてのリンクを取得して配列にスローします。

    @myLinks.each {|リンク| puts link.href } #etc など

于 2012-10-26T21:00:27.593 に答える
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"]
于 2012-10-26T21:29:07.280 に答える
0

I don't think that can be done with out-of-the box watir.

However it can be done, exactly as you have types, using '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
于 2012-10-26T19:45:38.257 に答える