我有一个简单的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的基础知识。谢谢。
发布于 2014-12-11 06:01:38
看一看open_uri_redirections的精华。
它为Ruby打了补丁,允许从OpenURI到HTTPS或相反方向的重定向。
发布于 2016-08-26 15:21:19
您也可以捕获异常,然后使用'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发布于 2017-09-26 19:42:41
Ruby2.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
https://stackoverflow.com/questions/27407938
复制相似问题