# CSSファイルをURLで指定して、 # CSS内で指定されているファイルを一括ダウンロードする # 2006/10/12 Jun Kaneko require 'net/http' require 'uri' Net::HTTP.version_1_2 # ファイルを保存 def get_file(download_url, filename) response = fetch(download_url,10) open(filename, "w") do |file| file.puts response.body end return filename end # HTTPリクエスト def fetch( uri_str, limit = 10 ) raise ArgumentError, 'http redirect too deep' if limit == 0 response = Net::HTTP.get_response(URI.parse(uri_str)) case response when Net::HTTPSuccess then response when Net::HTTPRedirection then fetch(response['Location'], limit - 1) else response.error! end return response end # ここからプログラム本体 # 第一引数 ARGV[0] はCSS のURL # 第二引数 ARGV[1] は、ファイル保存先のフォルダ css_uri = URI.parse(ARGV[0]) directory = css_uri.path[0..css_uri.path.rindex("/")] ARGV[1] != nil ? file_path = ARGV[1] + "/" : file_path = "" # CSSのURLから、CSSを読み込んで url() の中身を取得 images = Array.new images = fetch(ARGV[0],2).body.scan(/(url\()([\w._:\/\-]+)/) images.each do |image| # CSS内で指定されているURLからファイル名を切り出し filename = image[1].scan(/\/[\w._:\-]+/).last filename == nil ? filename = file_path + image[1] : filename = file_path + filename.gsub("/","") img_uri = "" case image[1] when /^(http)/ img_uri = image[1] when /^\// img_uri = "http://" + css_uri.host + image[1] when /^../ # ../ パス指定を処理する trees = image[1].split(/\//) chopped_path = "" chopped = 0 trees.each do |tree| if tree != ".." chopped_path += "/" + tree chopped += 1 end end trees = directory.split(/\//) chopped_directory = "" i = 0 while i < (trees.length - chopped) chopped_directory += "/" + trees[i] i += 1 end img_uri = "http://" + css_uri.host + chopped_directory + chopped_path else img_uri = "http://" + css_uri.host + directory + image[1] end print "Fetching : " + img_uri + "\n" get_file(img_uri, filename) end