2012-10-26 1 views
1

속성이 주어진 모든 링크를 얻을 수있는 방법이 있습니까? 이런 일을 할 수있는 방법이 있나요루비 - Watir 보석을 가져 오는 링크

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

: 나무 아래

, 나는이 태그를 많이 얻을 b.links(:class, "name")는과 거의 모든 div 이름을 클래스에서 출력 모든 하이퍼 링크 및 제목?

답변

1

명시 적으로 브라우저 개체의 특성에 대한 설명은 어떻게해야할까요? 그렇지 않으면 @ SporkInventor의 대답은 링크 속성에 대한 자리입니다.

@myLinks = Array.new 
@browser.divs(:class => "name").each do |d| 
    d.links.each {|link| @myLinks << link } 
end 
  1. 우리의 링크를 수집하는 새로운 배열을 만듭니다.
  2. "name"과 같은 클래스를 가진 브라우저의 모든 div에 대해 모든 링크를 잡고 배열로 던집니다.

    @ myLinks.each {| 링크 | link.href} #etc 등을두고

+0

모든 솔루션은 실제로 중대하다. 모두에게 점수를 줄 수 있기를 바랍니다. 정말 고맙습니다. –

0

나는 그것이 상자 밖의 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 
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"]