带字符串的http.get

时间:2010-11-19 09:56:51

标签: ruby http

我正在尝试使用http.get(字符串)下载af图片,其中字符串是url。字符串是未知的,每天都在变化。我把那个过去覆盖了。如果我打印字符串并将其粘贴到http.get中它可以正常工作。 为什么http.get不关心变量字符串?

require 'net/http'
Net::HTTP.start("apod.nasa.gov") { |http|
  resp = http.get("/apod/")
  resp.body.each{|line|
  if(line =~ /.jpg/)
    line.sub!("<a href=","")
    line.gsub!("\"","")
    resp = http.get(line)
    open("pic.jpg", "wb") { |file|
       file.write(resp.body)
    }
    break;
  end
  }
} 

sub with

    resp = http.get('/image/1011/cygnusNeb_geissinger1200.jpg')

它有效......

1 个答案:

答案 0 :(得分:0)

好的,现在就明白了。字符串行应该是chomped

require 'net/http'
Net::HTTP.start("apod.nasa.gov") { |http|
  resp = http.get("/apod/")
  resp.body.each{|line|
  if(line =~ /.jpg/)
    line.sub!("<a href=","")
    line.gsub!("\"","")
    line = "/" + line.chomp
    resp = http.get(line)
    open("apod.jpg", "wb") { |file|
       file.write(resp.body)
    }
    break;
  end
  }
}