2017-04-16 99 views
0

我写了一个Ruby脚本下载图片网址:如何用ruby“重新加载”cloudflare 520请求?

require 'open-uri' 

imageAddress = ARGV[0] 
targetPath = ARGV[1] 

fullFileNamePath = "#{targetPath}test.jpg" 

    begin 
    File.open(fullFileNamePath, 'wb') do |fo| 
     fo.write open(imageAddress).read 
     end 
    rescue OpenURI::HTTPError => ex 
    puts ex 
    File.delete(fullFileNamePath) 
    end 

实例应用:

ruby download_image.rb "https://images.genius.com/b015b15e476c92d10a834d523575d3c9.1000x1000x1.jpg" "/Users/Me/Downloads/" 

的问题是,有时候我碰到这个输出错误运行:

520 Origin Error

然后,当我在浏览器中尝试使用相同的URL时,我得到如下所示的内容:

enter image description here

如果我重新加载页面或单击上图中的“重试实时版本”按钮,页面将加载。

然后,如果我再次运行脚本它下载图像就好了。

那么我该如何复制这个页面重新加载/'重试的实时版本'的行为使用红宝石,而不切换到我的浏览器?再次运行脚本不会完成这项工作。

回答

0

这听起来像你正在寻找延迟命令。如果脚本失败(或遇到'520 Origin Error'),请等待并重试。

这是一个快速构建的递归函数,您可能希望添加其他检查多少次循环,打破这么多。 (也未经测试,可能包含错误,意为示例)

def getFile(params_you_need) 
    begin 
     File.open(fullFileNamePath, 'wb') do |fo| 
     fo.write open(imageAddress).read 
    end 
    rescue OpenURI::HTTPError => ex 
    puts ex 
    File.delete(fullFileNamePath) 
     if ex == '520 Origin Error' 
     sleep(30) #generally a good time to pause 
     getFile(params_you_need) 
     end 
    end 
end 
+0

原来,无论您等待多久都无所谓。它只有在你尝试它并在浏览器中重新加载然后再次调用脚本时才有效。 – kraftydevil

+0

最后一个想法(一对夫妇)取决于你想要走多远。你可以尝试使用系统通过命令行执行wget或curl,例如'system'wget url_to_file_or_image'' Nokoguri过去为我工作过,它有一些很好的功能可以连接到外部源。 –