Get image from url with cookies in ruby

吃可爱长大的小学妹 提交于 2019-12-11 09:27:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!