从URL获取图像与红宝石饼干(Get image from url with cookies in

2019-10-18 15:07发布

如你所知,一些验证码使用用户会话产生,我必须以某种方式保存到电脑这一形象,为了测试我们的应用程序,但如何,有什么更好的来的choise?

例如在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)

所以,也许,我有形象,我需要,但! 我怎么保存呢? 所有google'd文章说我,我必须用开放的URI,而是如何,我也必须使用会话? 也许我可以用红宝石HTTP类做不知何故?

因此,如何从加载的页面下载图片,或通过URL?

Answer 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)


文章来源: Get image from url with cookies in ruby