web-dev-qa-db-ja.com

Ruby open-uriリダイレクトは禁止されています

私が取り組んでいるこのシンプルな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基本。ありがとう。

35
Vikaton

open_uri_redirections gemをご覧ください。

RubyのOpenURIにパッチを適用して、HTTPからHTTPSへのリダイレクトまたはその逆を可能にします。

30
fivedigit

また、例外をキャッチして、「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/

16
kayn