【问题标题】:Get image from url with cookies in ruby使用 ruby​​ 中的 cookie 从 url 获取图像
【发布时间】:2013-09-16 14:19:55
【问题描述】:

如您所知,一些验证码是使用用户会话生成的,我必须以某种方式将此图像保存到计算机,以测试我们的应用程序,但是如何选择,以及选择什么更好?

例如在 http::get 我有这样的代码,带有 cookie:

http = Net::HTTP.new('***', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
path = '****'


# GET request -> so the host can set his cookies
resp, data = http.get(path)
body_text = resp.body
#puts "Body = #{body_text}"

cookie = resp.response['set-cookie'].split('; ')[0]
@captcha_url = (/BotDetectCaptcha.ashx?get=image&c=***;t=(.*)" \/>/.match body_text)
# POST request -> logging in
puts "captcha_url = #{@captcha_url}"
data = 'BotDetectCaptcha.ashx?get=image&c=****&t=#{@captcha_url}'
headers = {
  'Cookie' => cookie,
  'Referer' => '****',
  'Content-Type' => 'image-jpeg'
}

resp, data = http.post(path, data, headers)

所以,也许,我有我需要的图像,但是!我怎样才能保存它?所有 google 的文章都说我必须使用 open-uri,但是当我还必须使用 session 时怎么办?也许我可以用 ruby​​ 的 http 类以某种方式做到这一点?

那么我如何从加载的页面或通过 url 下载图像?

【问题讨论】:

  • 查看 mechanize gem,它允许您设置会话和下载文件。

标签: ruby http-headers open-uri


【解决方案1】:

您可以将图像获取到变量并保存:

IMG_PATH = '/var/www/pics/'

Class Img
  def self.download(data, filename)
    open(IMG_PATH + filename, 'wb') do |file|
      file << open(data).read
    end
    return true
  end
end

img = Img.download(data, filename)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-16
    • 2016-11-15
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 2021-04-12
    相关资源
    最近更新 更多