问题
As you know, some captchas are generating using user session, and i must to somehow save to computer this image, for testing our app, but how, and what better to choise?
For example on http::get i have such code, with cookies:
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)
so, perhaps, i have image that i need, but! how can i save it? All google'd articles say me, that i must use open-uri, but how to be, when i have to use session also? Maybe i could do it somehow with http class from ruby?
So how can i download image from loaded page, or via url?
回答1:
You can get image to variable and save it:
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)
来源:https://stackoverflow.com/questions/18830346/get-image-from-url-with-cookies-in-ruby