Share this post!

Build an Image Downloader in Ruby

Watch this video to learn how to build an image dowloader program step-by-step using Ruby, Nokogiri & RestClient!

Starting a new project & not sure where to start?

Write down a plan!

The plan for this project:

1. Request the HTML
2. Parse the HTML so we can work with it
3. Find the img tags
4. Find the image url from the img tag
5. Download the image & save it

In the video I explain every step in detail.


require 'nokogiri'
require 'rest-client'

html   = RestClient.get("").body
parsed = Nokogiri::HTML.parse(html)

image_tags = parsed.css("img")

image_tags.each do |img|
  url  = "http:#{img['src']}"
  name = url.split("/").last

  # Request image data
  file = RestClient.get(url).body

  # Save file in binary format
  File.write(name, file, mode: "wb")

Note: if you want to download BIG images you may have to use a different HTTP client because RestClient will buffer the entire image into memory & you may run out of memory.

If you found this video useful make sure to share it with your friends 🙂