有没有办法获得给定属性的所有链接?
在树下,我得到了很多这样的标签:
<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
对于浏览器中类等于“名称”的每个 div,抓取所有链接并将它们放入数组中。
@myLinks.each {|链接| 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