Use PhantomJS’s JavaScript APIs to capture a div, and let Ruby launch that script. PhantomJS does not provide a Ruby-native screenshot_div method. The reliable pattern is to open the page in a PhantomJS script, find the element with page.evaluate(), copy its bounding rectangle into page.clipRect, render the result, and invoke PhantomJS from Ruby.
This works for existing scripts, but PhantomJS development is suspended. Its QtWebKit engine can differ from current browsers, so treat this as a legacy-maintenance solution rather than a good default for new automation.
What the PhantomJS workflow actually does
PhantomJS renders a page through a JavaScript API. The relevant pieces are:
page.viewportSizesets the emulated browser viewport and therefore affects responsive layout.page.open()loads the URL and reports a status such assuccessor a failure.page.evaluate()runs code inside the loaded page. It can query the DOM and return simple serializable values.page.clipRectdefines a rectangle withtop,left,width, andheight.page.render()writes the clipped output. The filename extension selects the format supported by the PhantomJS build, including PNG and JPEG.
Without a clip rectangle, rendering captures the page according to PhantomJS’s normal page-rendering behavior. A fixed rectangle is suitable when coordinates are known in advance. For a particular div, derive coordinates from the element after the page has loaded.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
Prerequisites and file layout
- A PhantomJS executable available on the machine running the job.
- Ruby installed to orchestrate the process.
- A URL that PhantomJS can load and a CSS selector identifying the target element.
- A writable output directory.
Keep the browser code in a separate file so it can be tested independently from Ruby:
project/
capture_div.js
capture.rb
output/
Do not assume that a current Chrome-compatible page will render identically. PhantomJS uses an older WebKit implementation, so modern JavaScript, CSS, fonts, and security policies may require a compatibility adjustment or a different renderer.
Complete PhantomJS script for an element screenshot
Save this as capture_div.js. It accepts a URL, selector, output path, and optional viewport dimensions from the command line.
var system = require('system');
var webpage = require('webpage');
if (system.args.length < 4) {
console.log('Usage: phantomjs capture_div.js URL SELECTOR OUTPUT [WIDTH] [HEIGHT]');
phantom.exit(2);
}
var url = system.args[1];
var selector = system.args[2];
var output = system.args[3];
var width = parseInt(system.args[4] || '1366', 10);
var height = parseInt(system.args[5] || '900', 10);
if (!isFinite(width) || !isFinite(height) || width <= 0 || height <= 0) {
console.log('Viewport dimensions must be positive numbers.');
phantom.exit(2);
}
var page = webpage.create();
page.viewportSize = { width: width, height: height };
page.open(url, function (status) {
if (status !== 'success') {
console.log('Page load failed: ' + status);
phantom.exit(3);
}
var box = page.evaluate(function (cssSelector) {
var element = document.querySelector(cssSelector);
if (!element) {
return null;
}
var rect = element.getBoundingClientRect();
return {
top: rect.top + window.pageYOffset,
left: rect.left + window.pageXOffset,
width: rect.width,
height: rect.height
};
}, selector);
if (!box || box.width <= 0 || box.height <= 0) {
console.log('Element was not found or has no visible size: ' + selector);
phantom.exit(4);
}
page.clipRect = {
top: box.top,
left: box.left,
width: box.width,
height: box.height
};
page.render(output);
console.log('Saved ' + output);
phantom.exit(0);
});
The values returned from evaluate are ordinary numbers, not a DOM node. That distinction matters: the page-evaluation boundary is sandboxed, so you must pass simple values into the callback and return serializable data. A closure in the PhantomJS process is not available inside the page.
Recommended Free Tools
Why add the scroll offset?
getBoundingClientRect() reports coordinates relative to the viewport. page.clipRect needs page coordinates, so the script adds window.pageXOffset and window.pageYOffset. This keeps the clip aligned when the target is below the initial viewport.
Capturing a fixed rectangle instead
If the position never changes, skip DOM evaluation and assign known values:
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
page.clipRect = { top: 240, left: 80, width: 720, height: 420 };
page.render('output.png');
Fixed coordinates are simpler but become wrong when responsive layout, banners, fonts, or content changes the element’s position.
Run PhantomJS directly before adding Ruby
Test the browser script first. Replace the executable path with the path used on your system:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11phantomjs capture_div.js
'https://example.com'
'#pricing'
'output/pricing.png'
1440 1000
Use a CSS selector that is valid in document.querySelector(). Quote the URL and selector in your shell, especially when they contain &, spaces, brackets, or other shell characters.
Invoke the capture safely from Ruby
Ruby is the orchestration layer here. Use Open3.capture3 with an argument array instead of constructing one shell command string. The array form avoids accidental shell interpretation and gives you stdout, stderr, and the exit status.
require 'open3'
require 'fileutils'
phantomjs = ENV.fetch('PHANTOMJS', 'phantomjs')
script = File.expand_path('capture_div.js', __dir__)
url = ARGV.fetch(0, 'https://example.com')
selector = ARGV.fetch(1, '#pricing')
output = ARGV.fetch(2, File.expand_path('output/div.png', __dir__))
width = ARGV.fetch(3, '1366')
height = ARGV.fetch(4, '900')
FileUtils.mkdir_p(File.dirname(output))
stdout, stderr, status = Open3.capture3(
phantomjs,
script,
url,
selector,
output,
width,
height
)
unless status.success?
warn "PhantomJS failed (exit #{status.exitstatus})"
warn stderr unless stderr.empty?
warn stdout unless stdout.empty?
exit status.exitstatus || 1
end
puts stdout unless stdout.empty?
puts "Screenshot written to #{output}"
Run it with:
ruby capture.rb 'https://example.com' '#pricing' output/pricing.png 1440 1000
In production, validate URLs and output paths, impose a job timeout, retain the exit status, and record PhantomJS’s diagnostic output. Do not pass untrusted user input to a browser process without deciding which URLs and selectors your application is allowed to access.
Waiting for content before measuring the div
page.open indicates that the navigation completed, not that every application-rendered component is ready. A div may be empty while JavaScript, fonts, images, or an API request is still running. Add a page-appropriate readiness check before evaluating its geometry.
Wait for a selector with a bounded polling loop
function waitForSelector(page, cssSelector, maxMilliseconds, done) {
var started = new Date().getTime();
var timer = setInterval(function () {
var found = page.evaluate(function (s) {
var node = document.querySelector(s);
return !!node && node.getBoundingClientRect().width > 0 && node.getBoundingClientRect().height > 0;
}, cssSelector);
if (found) {
clearInterval(timer);
done(true);
} else if (new Date().getTime() - started >= maxMilliseconds) {
clearInterval(timer);
done(false);
}
}, 100);
}
// Call this after page.open succeeds:
waitForSelector(page, selector, 10000, function (ready) {
if (!ready) {
console.log('Timed out waiting for ' + selector);
phantom.exit(5);
}
// Measure the element and render here.
});
For pages that animate into place, disable the animation with injected CSS or wait until the application exposes a stable state. For lazy-loaded images, scroll the element into view and allow the image to load before measuring; otherwise the final dimensions can differ from the initial ones.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Choosing output format and image quality
Use an extension that matches your pipeline: .png for lossless UI text and transparency, or .jpg when a smaller photographic image is acceptable. PhantomJS builds can also support PDF, BMP, PPM, and GIF. Support and quality options depend on the Qt build, so verify the exact executable used by your deployment rather than assuming every build has identical codecs.
The clip rectangle is measured in CSS pixels. The resulting bitmap dimensions can therefore change with viewport, page zoom, and the renderer’s device-scale behavior. If exact pixel dimensions matter, pin the viewport and validate the generated file in your own environment.
Common failures and fixes
“Element was not found”
The selector may be wrong, the element may be inside an iframe, or the page may not have finished rendering. Inspect the selector in the page itself, wait for application content, and handle iframe content separately. A selector in the parent document cannot directly query a cross-document iframe.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
The image is blank or tiny
The element may have zero dimensions at capture time, be hidden by CSS, or depend on a delayed image/font. Check the returned width and height, wait for content, and capture after layout stabilizes.
The screenshot is horizontally or vertically offset
Check the coordinate system. Use document coordinates by adding the window scroll offsets, as in the complete script. Also check fixed-position elements and any page zoom or transforms that affect visual placement.
Modern pages fail to load
PhantomJS is suspended and its browser engine is old. Unsupported JavaScript syntax, TLS behavior, CSS features, or client-side security requirements can prevent a faithful render. Simplify the page for the legacy runtime, serve a compatible rendering route, or move the job to a maintained browser.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Ruby reports a missing executable
Set the full path through the PHANTOMJS environment variable and verify execute permissions:
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →PHANTOMJS=/opt/phantomjs/bin/phantomjs ruby capture.rb 'https://example.com' '#pricing' output/pricing.png
The process hangs
A page can keep network activity open indefinitely. Add a Ruby-level timeout around Open3.capture3, use PhantomJS page callbacks and timers, and terminate the process when your deadline expires. Always write partial diagnostics before retrying.
When this legacy approach is appropriate
Use it when you maintain an existing PhantomJS estate, need a local command-line renderer, and can accept the browser’s age. Keep viewport, selector, wait conditions, and output format explicit so captures are reproducible.
Choose another renderer when you need current browser behavior, modern JavaScript, dependable CSS compatibility, or long-term maintenance. A hosted renderer can also remove browser installation and process-management work, but evaluate its service terms, data handling, authentication, and network access for your application.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. One GET request can capture a URL, a selected element, a full page, or a PDF, with the selector and viewport options handled by the service. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
For the same kind of element capture, pass the selector and target URL to the API:
curl -G "https://api.screenshotneo.com/v1/shot"
-d access_key=YOUR_API_KEY
--data-urlencode url=https://example.com
--data-urlencode selector="#pricing"
-o shot.webp
See the complete parameter reference in the ScreenshotNeo documentation. The API also supports full-page captures with lazy images loaded, dark mode, device presets or custom viewports, retina scale, custom CSS and JavaScript, clicks, wait conditions, blocked requests, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous jobs, webhooks, bulk capture, usage reporting, and PDF options.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Python equivalent:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={
"access_key": "YOUR_API_KEY",
"url": "https://example.com",
"selector": "#pricing",
},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js equivalent:
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://example.com',
selector: '#pricing'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.
FAQ
Can I return the DOM element from page.evaluate?
No. Return serializable primitives such as numbers and strings, then assign those values to clipRect.
Does clipRect automatically select a div?
No. It clips a rectangle. Selecting a div requires querying its geometry first.
Can Ruby call PhantomJS without a wrapper gem?
Yes. Ruby can launch the PhantomJS executable directly; the PhantomJS page operations remain JavaScript.
Why does a fixed clip work on one viewport but not another?
Responsive layout changes element coordinates and dimensions. Derive the rectangle from the element after setting the intended viewport.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

