Ruby website screenshots

Ruby website screenshots

Generate website screenshots with Ruby and Rails

Sample code to take website screenshots in Ruby

require 'openssl'
require 'uri'
require 'net/http'
 
def urlbox(url, options={}, format='png')
  urlbox_apikey = 'YOUR_API_KEY'
  urlbox_secret = 'YOUR_API_SECRET'
 
  query = {
    :url         => url, # required - the url you want to screenshot
    :force       => options[:force], # optional - boolean - whether you want to generate a new screenshot rather than receive a previously cached one - this also overwrites the previously cached image
    :full_page   => options[:full_page], # optional - boolean - return a screenshot of the full screen
    :thumb_width => options[:thumb_width], # optional - number - thumbnail the resulting screenshot using this width in pixels
    :width       => options[:width], # optional - number - set viewport width to use (in pixels)
    :height      => options[:height], # optional - number - set viewport height to use (in pixels)
    :quality     => options[:quality] # optional - number (0-100) - set quality of the screenshot
  }
 
  query_string = URI.encode_www_form(query.reject {|k| query[k].nil? })
 
  token = OpenSSL::HMAC.hexdigest('sha256', urlbox_secret, query_string)
  urlbox = URI("https://api.urlbox.io/v1/#{urlbox_apikey}/#{token}/#{format}")
  urlbox.query = query_string
  urlbox
end
 
### USAGE: (format can be png or jpg, we default to png) ###
uri = urlbox("urlbox.io", {full_page: true, quality: 90}, 'jpg')
content = Net::HTTP.get(uri)
File.write("urlbox.jpg", content)