2013-09-16 42 views
1

正如你所知道的,一些验证码是使用用户会话生成的,我必须以某种方式保存到计算机上这个图像,以测试我们的应用程序,但是如何以及如何更好地选择?从红宝石中使用Cookie获取图像

例如在http ::让我有这样的代码,用饼干:

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) 

的话,或许,我有形象,我需要,但!我如何保存它?所有谷歌的文章都说我,我必须使用open-uri,但是如何成为,当我必须使用session时呢?也许我可以用ruby的http类以某种方式做到这一点?

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

+0

结账机械化的宝石,它允许您设置会话和下载文件。 – engineersmnky

回答

0

你可以得到图像变量,并将其保存:

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)