Skip to content

Instantly share code, notes, and snippets.

@satococoa
Created February 5, 2011 15:23
Show Gist options
  • Save satococoa/812521 to your computer and use it in GitHub Desktop.
Save satococoa/812521 to your computer and use it in GitHub Desktop.
画像ファイルダウンローダ
require 'nokogiri'
require 'open-uri'
require 'pathname'
url = ARGV[0]
dir = Pathname(ARGV[1])
unless dir.exist?
Dir::mkdir dir
end
doc = Nokogiri::HTML(open(url).read)
retrycount = 0
doc.css('a').each do |link|
if link['href'] =~ /\.(jpg|png|gif)$/
img = link['href']
dest = dir+File::basename(img)
puts "downloading #{img} to #{dest} ..."
begin
open(dest, 'wb'){ |f|
f.puts open(img).read
}
retrycount = 0
rescue Timeout::Error
retrycount += 1
if retrycount < 3
puts "retrying ..."
retry
end
end
end
end
puts 'mission complete!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment