有什么办法让所有的链接给定一个属性?红宝石 - Wa宝石抢链接
下的树,我得到了很多,这些标签:
<div class="name">
<a hef="http://www.example.com/link">This is a name</a>
</div>
有没有办法做这样的事情:b.links(:class, "name")
,它会输出来自所有div名称类的超链接和标题?
有什么办法让所有的链接给定一个属性?红宝石 - Wa宝石抢链接
下的树,我得到了很多,这些标签:
<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等于“name”的类,抓住所有链接并将它们放入数组中。
@ myLinks.each {| link |把link.href} #etc等
我不认为这可以用开箱即用的方式完成。
但是可以使用'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
我会用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"]
所有解决方案都是伟大的其实。希望我能给大家分。非常感谢。 –