Download Files with Ruby

Feb 17, 2010

This weekend, I remembered an old podcast I used to listen to that I wanted to hear again. It wasn't available on iTunes anymore, so I did a Google search for it. I found the show's Web site, and saw that they had a complete archive of all four seasons of the podcast (20 episodes per season). The problem was, each episode was on it's own page, with a separate page to access the download link. I started to manually try to download each episode, but that got old REALLY quickly. Why not write a simple script to do the work for me?

Here's the Ruby script I whipped up in about 15 minutes:

require 'net/http'

1.upto(4) do |season|
  1.upto(20) do |episode|
    episode = '%02d' % episode
    puts "Downloading Season ##{season}, Episode ##{episode}"
    Net::HTTP.start("website.com") do |http|
      resp = http.get("/episode_archive/s#{season}ep#{episode}.mp3")
      open("s#{season}ep#{episode}.mp3", "w") do |file|
    puts "Episode downloaded!"

puts "All files downloaded!!"

An explanation of what's going on here:

Lines #3-4: There are 4 seasons and 20 episodes per season, so iterate through them.
Line #5: We need to left pad the episode numbers, because that's how the files are named.
Line #7: Connect to the host.
Line #8: Get the episode (named like "s1ep05.mp3").
Lines #9-11: Save the file using the same name.

Tagged: rubyscript