How to screenshot a website/URL in Ruby
A common need is to convert a URL into a screenshot in PNG format. In this post we’ll cover how to do that in Ruby with just a few steps for free.
First, we need to install the Cloudmersive Convert gem. We can do that by adding this to our Gemfile:
gem 'cloudmersive-convert-api-client', '~> 1.2.9'
Or we can install it by running this command at the command line:
gem install cloudmersive-convert-api-client
Now all we need to do is call the convert_web_url_to_screenshot function with our chosen URL:
# load the gem
require 'cloudmersive-convert-api-client'
# setup authorization
CloudmersiveConvertApiClient.configure do |config|
# Configure API key authorization: Apikey
config.api_key['Apikey'] = 'YOUR API KEY'
api_instance = CloudmersiveConvertApiClient::ConvertWebApi.newinput = CloudmersiveConvertApiClient::ScreenshotRequest.new
input.Url = 'https://yahoo.com'begin
#Take screenshot of URL
result = api_instance.convert_web_url_to_screenshot(input)
rescue CloudmersiveConvertApiClient::ApiError => e
puts "Exception when calling ConvertWebApi->convert_web_url_to_screenshot: #{e}"
end
You’ll want to set input.Url to the URL in question that you would like to screenshot. You’ll also want to fill in your API Key — you can get one from the Cloudmersive website for free, good for 50,000 calls/month with no expiration.
Now you should be all set to generate your screenshots in PNG format from the input URL — all right from within Ruby.