使用ruby中的cookies从url获取图像
正如你们所知,一些验证码是使用用户会话生成的,我必须以某种方式将此图像保存到计算机上,以便测试我们的应用程序,但如何选择,以及选择什么更好 例如,在http::get上,我有这样的代码,带有cookie:使用ruby中的cookies从url获取图像,ruby,http-headers,open-uri,Ruby,Http Headers,Open Uri,正如你们所知,一些验证码是使用用户会话生成的,我必须以某种方式将此图像保存到计算机上,以便测试我们的应用程序,但如何选择,以及选择什么更好 例如,在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 c
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)
所以,也许,我有我需要的形象,但是!我怎样才能保存它?所有谷歌的文章都告诉我,我必须使用开放uri,但当我也必须使用会话时,如何使用开放uri呢?也许我可以用ruby的http类来实现它
那么,我如何从加载的页面或通过url下载图像?您可以将图像获取到变量并保存它:
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)
签出mechanize gem它允许您设置会话和下载文件。