熱門文章

2016年11月6日 星期日

[ruby]URI::InvalidURIError (bad URI(is not URI?)

我遇到這個error是在irb裡使用open-uri都正常,但是改寫成rb檔時出現的

/usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/uri/rfc3986_parser.rb:67:in `split': bad URI(is not URI?): http://google.com.au (URI::InvalidURIError)
from /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/uri/rfc3986_parser.rb:73:in `parse'
from /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/uri/common.rb:227:in `parse'
from /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/open-uri.rb:34:in `open'

from a.rb:16:in `<main>'


後來找到該解答如下

I got into trouble with URI.split (returning this error), I don't know if this helps you, but I will post here some warnings for also someone else having this error:
  1. Check your url is not nil, and it's a valid one.
  2. Do URI.encode(url) before URI.parse (to avoid special characters)
  3. Do strip to the string you pass to URI.parse (to avoid leading and trailing whitespaces).
All in one:
uri = URI.parse(URI.encode(url.strip))

解決方法:

puts "請輸入: "
html=gets.strip
在gets後面加上 .strip 去掉空白字元就行了



沒有留言:

張貼留言