Nerdery Watch
Scrubyt is a web-scraping toolkit for Ruby. It is awesome. Here’s a sample scrape:
!/usr/bin/env ruby
require 'rubygems'
require 'scrubyt'
du_data = Scrubyt::Extractor.define do
fetch 'http://mph.puddingbowl.org'
story do
title 'Does nothing escape the filthy clutches of these vi-rmin?'
cats 'software'
end
end
du_data.export(__FILE__)
du_data.to_xml.write($stdout, 1)
Scrubyt::ResultDumper.print_statistics(du_data)
The nutshell version: It goes out and grabs mph.puddingbowl.org, it takes a pair of examples for the things you want to scrape (title and categories), then generalizes those items by their DOM characteristics. The first time you scrape a site, you give it the examples based on the first item of the type you want to scrape on a given page. The “__FILE__” line exports the scrape as a generalization of your example items and produces a scrubyt script you can use in the future without having to provide any examples:
require 'rubygems'
require 'scrubyt'
du_data = Scrubyt::Extractor.define do
fetch 'http://mph.puddingbowl.org'
story "/html/body/div/div/div" do
title "/h2[1]/a[1]"
cats "/p[1]/a[1]"
end
end
du_data.to_xml.write($stdout, 1)
The output is in XML, which really doesn’t cause me to wince anymore, because as long as it’s consistent you don’t have to really work with it as XML if you’re of a mind to just munge the tags into something else.
The thing that blows me away is that it takes so little effort to do this. Creating objects and using them is so simple it freaks me out a little. Sixteen lines of code, three of which are reader-friendly whitespace, and you get an easy-to-read scraping script that pretty much wrote itself as far as the heavy lifting is concerned. Nice.
What’s not nice? One page I’d love to scrape has been built with an apparent desire to make HTML Tidy wish it had been born as a third year CS student’s porn spider.
Note: If you want to try it, get the 0.23 version of scrubyt. The 0.26 version is busted up for some things. It also seems to pay to just go with the MacPort, because Tiger’s default install is sorta busted up, too.
Second Note: Some time between last night and today, all the stuff I was doing that broke 0.26 is mysteriously working. Read any information I provide as if I am a blithering n00b and you’ll probably be fine.