【问题标题】:Ruby open-uri redirect forbiddenRuby open-uri 重定向被禁止
【发布时间】:2015-02-09 01:21:32
【问题描述】:

我有一个我一直在研究的简单的 html 解析器(用于学习目的)。:

require 'open-uri'
puts "Enter URL to parse HTML: "
url = gets.chomp
puts "Enter tag to parse from: "
tag = gets.chomp
response = open(url).read
title1 = response.index(tag)
title2 = response.index(tag.insert(1,'/')) -1
result = response[(title1 + tag.length - 1)..title2]
print result 

当我输入 http://twitter.com 时,我收到以下错误消息:

ERROR: `open_loop': redirection forbidden: http://twitter.com -> https://twitter.com/ (RuntimeError)
from /usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/2.1.0/open-uri.rb:149:in `open_uri'
from /usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/2.1.0/open-uri.rb:704:in `open'
from /usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/2.1.0/open-uri.rb:34:in `open'
from /home/ubuntu/workspace/htmlparse.rb:6:in `<main>' 

有什么建议或帮助吗?我是 Ruby 新手,我知道其他 html 解析模块,但我这样做是为了学习 Ruby 基础知识。谢谢。

【问题讨论】:

  • 我相信这是因为 twitter 使用了https。 FWIW - 如果您只是想学习和闲逛,您可能想访问 http://www.example.org 之类的网站而不是 twitter。
  • 我知道http://网站可以工作,但是我认为open-uri会自动重定向到https,https://twitter.com可以,但是http不行,有什么解决办法吗?
  • 我的建议:将该文件下载到您控制的某个服务器(github、bintray),这样它就可以避免重定向(抱歉不得不输入)

标签: ruby open-uri


【解决方案1】:

Ruby 2.4 修复了 open-uri 中的升级重定向(从 http -> https),所以现在:

RUBY_VERSION
=> "2.4.2"

require 'open-uri'
=> true

open('http://twitter.com')
=> #<Tempfile:/tmp/open-uri20170926-24254-1kflwxq>

来源:http://blog.bigbinary.com/2017/03/02/open-uri-in-ruby-2-4-allows-http-to-https-redirection.html

【讨论】:

    【解决方案2】:

    您也可以捕获异常,然后使用 'https' url 重试。

    url = "http://classic.ona.io/api/v1/files/3538545?filename=gringgo/attachments/1485229166168.jpg"
    
    uri = URI.parse(url)
    tries = 3
    
    begin
      uri.open(redirect: false)
    rescue OpenURI::HTTPRedirect => redirect
      uri = redirect.uri # assigned from the "Location" response header
      retry if (tries -= 1) > 0
      raise
    end
    

    来源:https://twin.github.io/improving-open-uri/

    【讨论】:

    • 比添加另一个依赖项来处理这个问题要优雅得多。
    • 太棒了!英镑的 sn-p,正是我所需要的。
    • 极好的答案 - 只是一个说明 - 使用这种方法,在 open() 调用中需要 redirect: false 以便打开抛出 OpenURI::HTTPRedirect 异常类型
    【解决方案3】:

    看看open_uri_redirections gem。

    它修补 Ruby 的 OpenURI 以允许从 HTTP 重定向到 HTTPS 或其他方式。

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      相关资源
      最近更新 更多