Musings of a Fondue

Scraping Pictures With Ruby

Another snippet!

I was trying to get some images from this site. They are part of an animation sequence of about 200 images.

At about the sixtieth image it got quite tedious to right click and save each image manually.

So, I did a quick Google search for “using ruby to grab images from a site” and came across this answer on StackOverflow.

Only four lines of code! Four!


open("http://www.somewebsite.com/61.jpg") {|f|
   File.open("61.jpg","wb") do |file|
     file.puts f.read
   end
}       

I modified it slightly with a for loop, and literally in a minute had all the images!


for i in 61..205
    url = "http://www.somewebsite.com/" + i.to_s + ".jpg"
    image = i.to_s + ".jpg"

    open(url) {|f|
        File.open(image, "wb") do |file|
            file.puts f.read
        end
    }
end

Awesome!!

Moments like this are really cool. So if you are finding yourself in a bit of a low on your programming journey, hang in there! It’s worth it. =)

Commented code,


require 'open-uri'  # loads the open-uri library

for i in 61..205    # loop -> start with i = 61, keep looping through the function each time incrementing i by 1, and
                    #         stop the loop when i = 205
    url = "http://www.somewebsite.com/" + i.to_s + ".jpg"   # ex. "www.somewebsite.com/62.jpg"
    imageName = i.to_s + ".jpg"                             # ex. "62.jpg"

    open(url) {|f|                               # open the website,
        File.open(imageName, "wb") do |file|     # open a new file called imageName, 
            file.puts f.read                     # put the contents of the url into the file
        end
    }
end

Btw, if you are a fan of the Iron Giant movie, checkout the site. It has amazing stuff like this storyboard art,

Comments