gpt4 book ai didi

ruby - GIF下载脚本中的错误处理

转载 作者:行者123 更新时间:2023-12-03 08:34:04 26 4
gpt4 key购买 nike

我正在学习编程的过程,所以我一直在提出一些随机项目。我决定制作一个脚本,以下载过去几年收集的所有GIF。似乎一切正常,除了我收到的错误中途发现我无法处理错误(错误的访问模式“wb”,“ArgumentError URI:HTTP资源是只读的”)之外,我已经整整一天的时间了,无法获得这项工作,将不胜感激任何帮助或提示。

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()

谢谢

最佳答案

gifname.gsub(/[^0-9a-z ]/i, '')行实际上不做任何事情,因为String#gsub方法不会修改String,但会返回修改后的字符串。
您需要改用String#gsub!:gifname.gsub!(/[^0-9a-z ]/i, '')
因此,gifname可能是HTTP URL,并且open-uri无法在写入模式下打开它,因为错误消息指出。

为了调试此类问题,您应该运行ruby调试器,或放置一堆puts语句来检查变量的内容。

关于ruby - GIF下载脚本中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15559943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com