【发布时间】: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 名称类的所有超链接和标题?
【问题讨论】:
有什么方法可以获取给定属性的所有链接?
在树下,我得到了很多这样的标签:
<div class="name">
<a hef="http://www.example.com/link">This is a name</a>
</div>
有没有办法做这样的事情:b.links(:class, "name") 它会输出所有 div 名称类的所有超链接和标题?
【问题讨论】:
明确地描述了关于属性的浏览器对象,这就是你必须这样做的方式。否则,@SporkInventor 的答案就是链接属性。
@myLinks = Array.new
@browser.divs(:class => "name").each do |d|
d.links.each {|link| @myLinks << link }
end
对于浏览器中类等于“name”的每个 div,抓取所有链接并将它们放入数组中。
@myLinks.each {|link| puts link.href } #etc 等
【讨论】:
在这种情况下,我会使用 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"]
【讨论】:
我认为开箱即用的 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
【讨论】: