2010-11-20 1 views
8

다음 HTML에 대해서는 구문 분석하고 Nokogiri를 사용하여 결과를 얻고 싶습니다.div 요소에서 Nokogiri를 사용하여 div를 내 보냅니다.

event_name = "folk concert 2" 
event_link = "http://www.douban.com/event/12761580/"  
event_date = "20th,11,2010" 

내가 doc.xpath('//div[@class="nof clearfix"]')div 요소를 얻을 수 알지만, 어떻게 event_name처럼 각각의 속성을 얻기 위해 진행해야하며, 특히 date? 내가 XPath를 모르는

<div class="nof clearfix">   
      <h2><a href="http://www.douban.com/event/12761580/">folk concert 2</a> <span class="pl2"> </span></h2> 
      <div class="pl intro"> 
       Date:25th,11,2010<br/> 
      </div> 
</div> 
<div class="nof clearfix">   
      <h2><a href="http://www.douban.com/event/12761581/">folk concert </a> <span class="pl2"> </span></h2> 
      <div class="pl intro"> 
       Date:10th,11,2010<br/> 
      </div> 
</div> 

답변

15

HTML, 나는 그들이 나에게 많은 의미를, CSS 선택기를 사용하는 것을 선호합니다. This tutorial이 유용 할 수 있습니다.

require 'rubygems' 
require 'nokogiri' 
require 'pp' 

Event = Struct.new :name , :link , :date 

doc = Nokogiri::HTML DATA 

events = doc.css("div.nof.clearfix").map do |eventnode| 
    name = eventnode.at_css("h2 a").text.strip 
    link = eventnode.at_css("h2 a")['href'] 
    date = eventnode.at_css("div.pl.intro").text.strip 
    Event.new name , link , date 
end 

pp events 


__END__ 
<div class="nof clearfix">   
     <h2><a href="http://www.douban.com/event/12761580/">folk concert 2</a> <span class="pl2"> </span></h2> 
      <div class="pl intro"> 
      Date: 25th,11,2010<br/> 
      </div> 
</div> 
<div class="nof clearfix">   
     <h2><a href="http://www.douban.com/event/12761581/">folk concert </a> <span class="pl2"> </span></h2> 
      <div class="pl intro"> 
      Date: 10th,11,2010<br/> 
      </div> 
</div> 

이 출력 : 나는 완벽하게 작동

[#<struct Event 
    name="folk concert 2", 
    link="http://www.douban.com/event/12761580/", 
    date="Date: 25th,11,2010">, 
#<struct Event 
    name="folk concert", 
    link="http://www.douban.com/event/12761581/", 
    date="Date: 10th,11,2010">] 
+0

. 감사. – pierrotlefou