0
我正在学习编程,所以我一直在想一些随机项目。我决定编写一个脚本,下载我过去几年收集的所有GIF。似乎一切似乎工作,除了我收到一半的错误,我的错误处理没有捕获(无效访问模式“wb”,“ArgumentError URI:HTTP资源是只读的)。我一直在摆弄一整天,不能得到这个工作的任何帮助或建议,将不胜感激。GIF下载脚本中的错误处理
require 'json', 'open-uri'
def download
file = open("C:/sites/bookmark/gifs.json")
json = file.read
parsed = JSON.parse(json)
gifs = parsed["children"]
file.close()
total = 0
gifsize = 0
gifs.each do |key|
source = "#{key["uri"]}"
source.chomp
gifname = "#{key["title"]}"
gifname.gsub(/[^0-9a-z ]/i, '')
open("#{gifname}.gif", "wb") do |file|
begin
open(source)
rescue Exception => e
case e.message
when /404/ then puts '404!'
when /505/ then puts '505!'
when /408/ then puts '408!'
else puts 'idk #{e.message}'
end
file.close()
File.delete("#{gifname}.gif")
puts "Deleted #{key["title"]}.gig"
next
end
open(source) do |uri|
file.write(uri.read)
total += 1
gifsize += (uri.size/1024)
print "#{(uri.size)/1024} KiloBytes"
end
print " --- #{total}"
end
puts " next gif---"
end
puts "\n#{gifsize} Total KB Downloaded \n#{total} Total Gifs "
end
download()
感谢
它的工作,非常感谢!我不知道是什么添加'!'对gsub做了。 – MattLock 2013-03-21 23:40:50
这是很多方法使用的常见Ruby成语。在开发时,调试语句和Ruby Doc(http://www.ruby-doc.org/)是你最好的朋友。 – nbarraille 2013-03-21 23:47:47