有什麼辦法讓所有的鏈接給定一個屬性?紅寶石 - 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"]
所有解決方案都是偉大的其實。希望我能給大家分。非常感謝。 –