ScreenshotNeo

BlogHow-to

How to Screenshot Specific Page Divs with Ruby and PhantomJS

Capture a specific div with Ruby and PhantomJS using DOM geometry, clipRect, reliable waits, troubleshooting, and a hosted alternative.

By the ScreenshotNeo team30 September 20268 min read

How to Screenshot Specific Page Divs with Ruby and PhantomJS

To screenshot one specific div with Ruby and PhantomJS, let PhantomJS inspect the loaded DOM, read the element’s coordinates, assign those coordinates to page.clipRect, and call page.render. Ruby starts PhantomJS and checks its result; the page interaction itself is JavaScript because PhantomJS exposes its screenshot API through JavaScript.

The reliable sequence is:

  1. Choose the viewport size before loading the page.
  2. Open the URL and verify the load status.
  3. Wait until the page state you need is ready.
  4. Use page.evaluate to find the element and return serializable numeric geometry.
  5. Set page.clipRect and render to a named image file.
  6. Have Ruby check the child process status and stderr.

How PhantomJS clips a screenshot

PhantomJS does not provide a separate “screenshot this selector” method. Its documented clipping API is a rectangle with top, left, width, and height. Without a clip rectangle, page.render captures the full page. The rectangle can be fixed, or it can be calculated from a live DOM element.

A selector becomes page coordinates before PhantomJS renders the clipped rectangle.
A selector becomes page coordinates before PhantomJS renders the clipped rectangle.

The fixed form is useful when a layout is completely known:

page.clipRect = {
  top: 120,
  left: 40,
  width: 640,
  height: 360
};
page.render('panel.png');

For a real page, derive the rectangle after layout. getBoundingClientRect() reports viewport coordinates, so add the document scroll offsets to obtain page coordinates. Return plain numbers across the evaluate boundary; do not return a DOM node, a function, or an object containing browser-only references. The official evaluate API describes this sandbox boundary.

Complete PhantomJS script for one div

Save this as screenshot_div.js. It accepts a URL, CSS selector, output filename, and an optional delay in milliseconds. The delay is useful for client-rendered content, web fonts, lazy images, or a page animation that must settle before measurement.

var system = require('system');
var webpage = require('webpage');

if (system.args.length < 4) {
  console.error('Usage: phantomjs screenshot_div.js URL SELECTOR OUTPUT [DELAY_MS]');
  phantom.exit(2);
}

var url = system.args[1];
var selector = system.args[2];
var output = system.args[3];
var delay = parseInt(system.args[4] || '0', 10);
if (isNaN(delay) || delay < 0) {
  delay = 0;
}

var page = webpage.create();
page.viewportSize = {
  width: 1366,
  height: 900
};

page.onError = function (message, trace) {
  console.error('page error: ' + message);
};

function fail(message, code) {
  console.error(message);
  phantom.exit(code || 1);
}

page.open(url, function (status) {
  if (status !== 'success') {
    fail('Could not load ' + url + ' (status: ' + status + ')');
    return;
  }

  window.setTimeout(function () {
    var box = page.evaluate(function (targetSelector) {
      var element = document.querySelector(targetSelector);
      if (!element) {
        return null;
      }

      var rect = element.getBoundingClientRect();
      var style = window.getComputedStyle(element);
      var width = rect.width;
      var height = rect.height;

      return {
        top: rect.top + (window.pageYOffset || document.documentElement.scrollTop || 0),
        left: rect.left + (window.pageXOffset || document.documentElement.scrollLeft || 0),
        width: width,
        height: height,
        display: style.display,
        visibility: style.visibility
      };
    }, selector);

    if (!box) {
      fail('Selector did not match an element: ' + selector);
      return;
    }
    if (box.width <= 0 || box.height <= 0) {
      fail('Matched element has no visible area: ' + selector);
      return;
    }
    if (box.display === 'none' || box.visibility === 'hidden') {
      fail('Matched element is hidden: ' + selector);
      return;
    }

    page.clipRect = {
      top: box.top,
      left: box.left,
      width: box.width,
      height: box.height
    };

    page.render(output);
    console.log('Saved ' + output);
    phantom.exit(0);
  }, delay);
});

Run it directly from a shell:

phantomjs screenshot_div.js \
  'https://example.com/article' \
  '#pricing-panel' \
  'pricing-panel.png' \
  1000

The filename extension selects the output format. The documented render method supports image formats including PNG and JPEG, and some Qt builds also support PDF, BMP, PPM, and GIF. PNG is usually the safest choice for text and sharp UI edges.

Ruby orchestration with safe arguments

There is no official Ruby-native screenshot_div API in PhantomJS. Ruby’s role is to invoke the PhantomJS executable, pass arguments safely, and fail when the process reports an error. Using Open3.capture3 avoids constructing one shell command string that could be misquoted when a URL or selector contains punctuation.

#!/usr/bin/env ruby
require 'open3'

url = ARGV.fetch(0, 'https://example.com/article')
selector = ARGV.fetch(1, '#pricing-panel')
output = ARGV.fetch(2, 'pricing-panel.png')
delay_ms = ARGV.fetch(3, '1000')

phantomjs = ENV.fetch('PHANTOMJS_BIN', 'phantomjs')
script = File.expand_path('screenshot_div.js', __dir__)

stdout, stderr, status = Open3.capture3(
  phantomjs,
  script,
  url,
  selector,
  output,
  delay_ms
)

unless status.success?
  warn stderr unless stderr.empty?
  warn stdout unless stdout.empty?
  abort "PhantomJS failed with exit status #{status.exitstatus}"
end

puts stdout unless stdout.empty?
puts "Created #{output}"

Example:

ruby capture.rb \
  'https://example.com/article' \
  'div.card.featured' \
  'featured-card.png' \
  1500

Choosing the right element rectangle

Fixed coordinates versus DOM-derived coordinates

Approach Use it when Risk
Fixed clipRect The page and viewport are stable and you need a repeatable region. A responsive layout or content change can move the target.
Selector plus getBoundingClientRect() The target’s position changes with content, viewport, or responsive CSS. A missing, hidden, or zero-sized element must be handled.

Viewport size changes the result

Set page.viewportSize before page.open. A different width can change breakpoints, wrapping, font sizes, and the element’s height. Pick the dimensions that match the screenshot consumers. If you need desktop and mobile versions, run separate captures with explicit viewport settings rather than assuming one rectangle works for both.

Full-page elements and overflow

An element can be taller than the initial viewport. PhantomJS still uses the page-coordinate rectangle returned by the DOM. If the page uses an internal scrolling container, measure the container’s visible box or temporarily adjust its scroll position in evaluate; the document’s scroll offset alone does not describe every nested scroller.

Margins, borders, and shadows

getBoundingClientRect() includes the element’s border box. It does not include an outside box shadow. If a shadow must appear, expand top, left, width, and height by a deliberate number, while clamping the rectangle to the page. If you need only the content box, subtract the computed border widths.

Waiting for the page to be ready

page.open reports the navigation result, not that every asynchronous component has finished. Use the smallest readiness rule that matches the page:

  • Wait for a selector that proves the component exists.
  • Use a short delay for fonts, transitions, or a known client-rendered update.
  • Disable animations with injected CSS when motion changes the measured rectangle.
  • Scroll the target into view if the page only loads images near the viewport.

For a selector-based wait, replace the fixed delay with polling:

function waitForSelector(selector, callback, attempts) {
  if (attempts <= 0) {
    callback(false);
    return;
  }
  var found = page.evaluate(function (s) {
    return !!document.querySelector(s);
  }, selector);
  if (found) {
    callback(true);
    return;
  }
  window.setTimeout(function () {
    waitForSelector(selector, callback, attempts - 1);
  }, 250);
}

waitForSelector('#pricing-panel', function (found) {
  if (!found) {
    fail('Timed out waiting for #pricing-panel');
    return;
  }
  // Measure the element and render here.
}, 40);

Common errors and fixes

Symptom Cause Fix
Selector did not match The selector is wrong, the route redirected, or the app has not rendered. Inspect the selector in the page, wait for the app’s ready state, and log the final URL if redirects matter.
Blank or tiny image The element has zero dimensions, is hidden, or was measured before layout. Check width and height, wait longer, and verify computed display and visibility.
Wrong crop after scrolling Viewport coordinates were used as page coordinates. Add pageXOffset and pageYOffset as shown in the script.
Modern page fails to load PhantomJS uses an old QtWebKit engine and development is suspended. Use a compatible page, simplify the required rendering, or move to a maintained browser or hosted renderer.
Fonts or images are missing Rendering happened before resources completed, or the resource is blocked. Wait for a page-specific condition, allow the required resources, and avoid relying on a single arbitrary delay.
Ruby reports success but no useful file exists The script rendered an unexpected path or the rectangle was invalid. Use an absolute output path, check the file after the process exits, and fail on zero-sized geometry.
Shell quoting errors URL or selector characters were interpreted by the shell. Pass each argument separately through Open3.capture3.

Reliability, performance, and cost considerations

Measure only after the page state is stable. A very short delay is fast but may capture an incomplete component; an unnecessarily long delay increases job time without improving the image. Selector polling gives you a bounded timeout and a meaningful failure when the target never appears.

For repeated jobs, reuse the same script and keep viewport, selector, and output conventions explicit. Record the URL, selector, viewport, delay, PhantomJS version, exit status, and output path. Retry navigation failures with a limit, but do not blindly retry a deterministic missing-selector error.

PhantomJS is a local executable, so direct monetary cost depends on the machine and operations that run it. The project homepage states: “Important: PhantomJS development is suspended until further notice.” That makes browser compatibility and long-term maintenance a central tradeoff for new automation. The official PhantomJS homepage, screen capture guide, and clipRect documentation are the primary references for the APIs used here.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. Its endpoint returns a PNG, JPEG, WebP, or PDF from one GET request, and its options include capturing one element by CSS selector, full-page capture, custom viewport and device presets, retina scale, waits, custom CSS and JavaScript, hidden selectors, headers, cookies, user agents, geolocation, caching, and asynchronous jobs. See the ScreenshotNeo documentation for the element and rendering options.

A hosted screenshot workflow can remove common overlays before capture.
A hosted screenshot workflow can remove common overlays before capture.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result. An MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

FAQ

Can I return the DOM element from page.evaluate?

No. Return serializable values such as numbers and strings, then assign those values to page.clipRect.

Does clipRect select by CSS selector?

No. It accepts coordinates. The selector lookup and geometry calculation are the composition shown in this guide.

What if there are several matching divs?

Use a more specific selector, or return an indexed match from document.querySelectorAll and validate the chosen rectangle.

Should I use PNG or JPEG?

Use PNG for text-heavy panels and transparency. Use JPEG when a smaller photographic image is more important than lossless edges.

Is PhantomJS suitable for a new production renderer?

It can run existing scripts, but its suspended development and older rendering engine should be weighed against a maintained browser or hosted rendering service.