2010-11-20 22 views
8

ile alınmasını sağlayın. Aşağıdaki HTML için onu ayrıştırmak ve Nokogiri'yi kullanarak aşağıdaki sonucu elde etmek istiyorum.div işlevine sahip div öğesinin Nokogiri

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

Ben doc.xpath('//div[@class="nof clearfix"]') her div eleman alabilir biliyorum ama nasıl event_name gibi her atıf almak için devam etmelidir ve özellikle date? Ben XPath'leri bilmiyorum

<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> 

cevap

15

HTML, onlar bana daha mantıklı, css seçiciler kullanmayı tercih ediyorum. This tutorial sizin için yararlı olabilir.

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> 

Bu çıkışlar: Ben mükemmel çalışıyor

[#<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

. Teşekkürler. – pierrotlefou