Guest User

National Gallery scraper

a guest
Apr 15th, 2013
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.78 KB | None | 0 0
  1. require 'builder'
  2. require 'nokogiri'
  3.  
  4. BASE_URL = 'http://www.nga.gov'
  5. FEED_URL = BASE_URL + '/programs/calendar/'
  6.  
  7. def national_gallery_of_art(page)
  8.   doc = Nokogiri::HTML page
  9.  
  10.   xml = Builder::XmlMarkup.new :indent => 2
  11.   xml.instruct! :xml, :version => 1.0, :encoding => 'utf-8'
  12.  
  13.   xml.feed(:xmlns => 'http://www.w3.org/2005/Atom') do |feed|
  14.     feed.title 'National Gallery of Art'
  15.     feed.link :href => FEED_URL
  16.     feed.author do |author|
  17.       author.name 'National Gallery of Art'
  18.     end
  19.  
  20.     # feed.updated
  21.     # feed.id ?
  22.  
  23.     #each anchor corresponds to a day
  24.     anchors = doc.xpath("//a[starts-with(@id, 'date')]").to_a.map {|a| a['id']}
  25.  
  26.     anchors.each_index do |i|
  27.       path = <<-XPATH
  28.       //div[@class='event-grouping'
  29.             and preceding-sibling::a[@id='#{anchors[i]}']][1]
  30.       XPATH
  31.  
  32.       day = doc.xpath(path).text
  33.  
  34.       # select all events between two consecutive anchors
  35.       path = "//div[@class='coe-list' and preceding-sibling::a[@id='#{anchors[i]}'] "
  36.  
  37.       if i < anchors.length - 1
  38.         path << " and following-sibling::a[@id='#{anchors[i+1]}']"
  39.       end
  40.  
  41.       path << "]"
  42.  
  43.       events = doc.xpath path
  44.       time = events.first.xpath("span[@class='time'][1]").text.strip
  45.  
  46.       events.each do |event|
  47.         new_time = event.xpath("span[@class='time']").first
  48.         if new_time
  49.           time = new_time.text.strip
  50.         end
  51.  
  52.         div = event.xpath("div[@class='event'][1]")
  53.         title = div.text
  54.         link = BASE_URL + div.xpath('a[1]').attr('href')
  55.  
  56.         feed.entry do |entry|
  57.           entry.title title, :type => 'text'
  58.           entry.link link
  59.           entry.summary "#{day}, #{time}", :type => 'text'
  60.         end      
  61.       end
  62.     end
  63.  
  64.   end # xml.feed
  65.  
  66.   xml.target!
  67. end
Advertisement
Add Comment
Please, Sign In to add comment