Skip to content

Instantly share code, notes, and snippets.

@peterc
Created May 21, 2010 04:55
Show Gist options
  • Save peterc/408477 to your computer and use it in GitHub Desktop.
Save peterc/408477 to your computer and use it in GitHub Desktop.
XKCD for iPad
#!/bin/env ruby
require 'rubygems'
require 'open-uri'
require 'nokogiri'
doc = Nokogiri::HTML(open('http://xkcd.com/').read)
puts %{Content-type: text/html
<html><head><title>XKCD for iPad</title>
<style type="text/css">BODY { font-family: helvetica; font-size: 16px; text-align: center}
.quip { font-style: italic }</style></head><body>
#{doc.css("h1")}
<p>#{doc.css("img").detect { |x| x.attr('src') =~ /comics/ }}</p>
<p class="quip">#{(doc.css("img").detect { |x| x.attr('src') =~ /comics/ }).to_s[/title=\"(.*?)\"/, 1]}</p>
</body></html>}
# Totally too much in a hurry to bother figuring out the correct XPath expressions for the above shite ;-)
# But feel free to give it a go!
@caius
Copy link

caius commented May 21, 2010

Few points I noticed in reading it initially ;)

  • Shebang should be #!/usr/bin/env ruby
  • XPath isn't needed - and you're using css() already, just add more css selectors to make it specific!
  • Can get an attribute from an element by using Element#[] in Nokogiri - doc.css("img")[:title]

@peterc
Copy link
Author

peterc commented May 21, 2010

Cool, didn't know about the attribute thing.

Also, /bin/env is fine on most Linux, which is where I did it. But, yeah, on OS X it doesn't work.. (but WTF deploys to OS X anyway..) :-)

@caius
Copy link

caius commented May 21, 2010

People with headless mac servers sat on their office windowsill. cough

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment