【问题标题】:Open-uri throwing error => (URI::InvalidURIError)Open-uri 抛出错误 => (URI::InvalidURIError)
【发布时间】:2016-03-17 17:38:06
【问题描述】:

我有一个用于测试目的的程序,我正在做的是在网络上抓取开放代理,并记录它们的信息,但是这是一种非常不同类型的代理抓取工具,因为它会创建一堆在执行之前在文件内部之前的随机代理,例如:

def create_possibles
  puts "Creating random possible proxies..".green.bold
  1.times do 
    port = rand(2000..8080)
    1.times do 
      ip = Array.new(4){rand(256)}.join('.')
      possible_proxy = "#{ip}:#{port}"
      File.open("possible_proxies.txt", "a") {|s| s.puts(possible_proxy)}
    end
  end
end
#<= 189.96.49.87:7990

我想用那个“可能的代理”做的是打开它,看看它是否有效,但是当我使用以下代码时,它只会抛出该错误:

def check_possibles
  IO.read("possible_proxies.txt").each_line do |proxy|
    puts open('http://google.com', :proxy => "http://#{proxy}")
  end
end

我有两个问题:

  1. 这是否意味着代理无效,如果是,有没有办法跳过文件中的行?可能通过使用nextskip
  2. 如果这并不意味着代理无效,那么这意味着什么,我在代码中做错了什么导致它读取 url 错误?

完全错误:

C:/Ruby22/lib/ruby/2.2.0/uri/rfc3986_parser.rb:66:in `split': bad URI(is not URI
?): http://189.96.49.87:7990 (URI::InvalidURIError)

编辑:

有人告诉我尝试URI.parse,但我得到了同样的错误:

C:/Ruby22/lib/ruby/2.2.0/uri/rfc3986_parser.rb:66:in `split': bad URI(is not URI
?): http://195.239.61.210:4365 (URI::InvalidURIError) #<= Different IP

【问题讨论】:

  • 我完全感到困惑,http://189.96.49.87:7990 是一个完全有效的 URI。当您尝试URI.parse("http://#{proxy}") 时会发生什么?
  • @shelvacu 我不知道,让我很快找出答案
  • @shelvacu 我尝试使用不同的 IP C:/Ruby22/lib/ruby/2.2.0/uri/rfc3986_parser.rb:66:in `split': bad URI(is not URI ? ): 195.239.61.210:4365 (URI::InvalidURIError)

标签: ruby proxy open-uri


【解决方案1】:

当您使用#each_line 遍历ruby 中的每一行时,它会为您提供每一行包括换行符。 Ruby 的 URI 库不喜欢换行符。简单替换

:proxy => "http://#{proxy}"

:proxy => "http://#{proxy.chomp}"

String#chomp 将切断字符串末尾的所有换行符。

【讨论】:

  • 你是我的主和救世主!我完全忘记了.chomp 哈哈,非常感谢!
猜你喜欢
  • 2012-02-23
  • 2011-07-19
  • 2012-04-09
  • 1970-01-01
  • 2017-12-18
  • 2015-07-02
  • 1970-01-01
  • 2018-04-08
  • 2020-06-11
相关资源
最近更新 更多