Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

IMGKit has no documented CSS-selector option for capturing one element. To screenshot a specific <div>, either render an isolated HTML document containing that element, or render the full page and crop a known pixel rectangle with wkhtmltoimage’s crop-x, crop-y, crop-w, and crop-h options. Isolation is usually more reliable because responsive layout, fonts, margins, and JavaScript can move a coordinate-based crop.

What IMGKit can and cannot select

IMGKit is a Python 2 and 3 wrapper around the wkhtmltoimage command-line utility. Its documented entry points are from_url, from_file, and from_string. The wrapper does not document an argument such as selector="#invoice" that asks wkhtmltoimage to find and capture one DOM node.

That leaves two dependable methods:

  • Isolate the element: create a small HTML document containing the target div and the styles it needs, then call imgkit.from_string.
  • Crop rendered coordinates: capture the original page and provide the target rectangle in pixels with the four crop options.

Use isolation when you control the markup or can obtain it. Use coordinates when the original page must be rendered intact and the element’s position is stable.

Method 1: render an isolated div (recommended)

Install the Python wrapper and renderer

Install IMGKit with pip:

python -m pip install imgkit

IMGKit is only a wrapper; you also need the wkhtmltoimage executable installed and available on your PATH. On a server where it is installed elsewhere, configure its explicit path:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import imgkit

config = imgkit.config(wkhtmltoimage="/usr/local/bin/wkhtmltoimage")

If the executable is not discoverable, conversion fails before any HTML is rendered. On headless Linux, the project documentation recommends Xvfb; pass its configuration when a display is required by your installation.

Minimal isolated capture

import imgkit

html = """
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    html, body { margin: 0; padding: 0; }
    #capture { display: block; }
    /* Copy the target's real styles here. */
  </style>
</head>
<body>
  <div id="capture">
    <h1>Monthly report</h1>
    <p>Rendered as a tight image.</p>
  </div>
</body>
</html>
"""

options = {
    "format": "png",
    "quiet": "",
}

imgkit.from_string(html, "div.png", options=options)

The output is written to div.png. Resetting both html and body margins prevents the browser’s default whitespace from appearing around the element. Include the target’s actual font declarations, widths, colors, and layout rules; otherwise the isolated copy can have different dimensions from the page you see in a browser.

Extracting a div from an existing document

If your application already has the HTML, parse it, copy the selected node into a new document, and include the CSS required by that node. The important operation is not a hidden IMGKit selector; it is producing a valid, self-contained render input:

from pathlib import Path
import imgkit

page = Path("page.html").read_text(encoding="utf-8")
# Supply `target_html` from your own HTML parser after selecting the div.
target_html = '<div id="capture" class="card">Report</div>'

isolated = f"""
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    html, body {{ margin: 0; padding: 0; }}
    .card {{ width: 640px; padding: 24px; background: white; }}
  </style>
</head>
<body>{target_html}</body>
</html>
"""

imgkit.from_string(isolated, "card.png", options={"format": "png", "quiet": ""})

Do not copy only the element’s markup when it depends on ancestor selectors, CSS variables, web fonts, pseudo-elements, or JavaScript-created children. Bring those dependencies into the isolated document or the visual result will change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Method 2: crop a full-page render by coordinates

When you must render https://example.test/page as-is, wkhtmltoimage exposes a capture window. The values are pixel coordinates in the rendered page:

  • crop-x: left coordinate.
  • crop-y: top coordinate.
  • crop-w: crop width.
  • crop-h: crop height.
import imgkit

options = {
    "format": "png",
    "crop-x": "120",
    "crop-y": "80",
    "crop-w": "640",
    "crop-h": "360",
    "screenWidth": "1280",
    "quiet": "",
}

imgkit.from_url("https://example.test/page", "div.png", options=options)

These coordinates refer to the rendered page, not CSS source coordinates or browser developer-tools coordinates at an arbitrary viewport. A responsive breakpoint, default margin, zoom level, font substitution, or different screen width can move the div. Set a stable screenWidth, reset margins in the page when possible, and measure the rectangle under the same rendering conditions used by IMGKit.

smartWidth can affect the output width. For repeatable jobs, explicitly control page and viewport dimensions rather than relying on automatic sizing.

Styles, dimensions, and output formats

Adding CSS

IMGKit accepts external stylesheets through its css argument, or you can embed a style block in the HTML:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
imgkit.from_string(
    html,
    "div.png",
    css=["reset.css", "card.css"],
    options={"format": "png", "quiet": ""},
)

For a pixel-tight image, include the target’s real box model and reset page margins. If the page loads a web font, make sure the renderer can reach it and allow enough time for it to load.

Choosing PNG, JPEG, or SVG

The documented image settings support PNG, JPG, BMP, and SVG. PNG is the best diagnostic format because it preserves transparency and sharp edges. JPEG quality is configurable, but it introduces compression artifacts around text and UI edges. PNG and SVG transparency are supported by the underlying image settings when the page background is transparent.

JavaScript and asynchronous content

wkhtmltoimage can enable or disable JavaScript and provides load.jsdelay, a delay in milliseconds after page load before rendering. Use it when the div is populated by client-side code:

options = {
    "format": "png",
    "load.jsdelay": "1500",
    "quiet": "",
}
imgkit.from_url("https://example.test/dashboard", "dashboard.png", options=options)

There is no universal delay that works for every site. Choose a value based on when the target reaches its final dimensions, and keep those dimensions stable. A delay cannot fix a blocked script, a failed API request, or a selector that never exists. For an isolated document, pre-render the content in Python when possible; that removes timing uncertainty.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Headless-server setup

On a workstation, IMGKit can usually invoke wkhtmltoimage directly. On a Linux server without a display, install and run Xvfb as recommended by the project documentation, then pass the appropriate xvfb configuration. Also verify that fonts, certificates, DNS, and outbound network access exist in the service account’s environment. A capture that works interactively can fail under a restricted worker user because it cannot read fonts or reach the source URL.

Troubleshooting checklist

“No wkhtmltoimage executable found”

  • Install wkhtmltoimage and confirm it is on PATH.
  • Call imgkit.config(wkhtmltoimage="/absolute/path/wkhtmltoimage") when it is installed elsewhere.

The image has extra whitespace

Set html, body { margin: 0; padding: 0; } in the isolated document. For coordinate crops, remember that the source page’s margins are part of the rendered coordinate system.

The crop contains the wrong content

Fix screenWidth, zoom, fonts, and responsive breakpoints. Re-measure x, y, width, and height at that exact configuration. Coordinate crops are not selector-aware.

Dynamic content is missing

Confirm JavaScript is enabled, add an appropriate load.jsdelay, and check that the network request succeeds. If possible, render already-complete HTML with from_string.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Transparency or text looks wrong

Diagnose with PNG, include the actual CSS and fonts, and remove unexpected page backgrounds. Switch to JPEG only when a smaller, opaque image is required.

Conversion exits or segfaults

Run the command shown in IMGKit’s exception and inspect wkhtmltoimage’s stderr. The project notes that some versions can fail with segmentation faults; test a minimal isolated document to distinguish an installation problem from page-specific HTML or resources.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost decisions

Isolation generally reduces page size, third-party requests, layout work, and timing variability. Full-page coordinate cropping preserves the original page but pays the cost of loading everything and is sensitive to layout drift. Neither the IMGKit project nor the inspected wkhtmltoimage settings publish a benchmark comparing these approaches, so choose based on your page’s dependencies rather than an assumed speed advantage.

For batch jobs, reuse a stable HTML template, set deterministic viewport dimensions, avoid unnecessary remote assets, and record the exact options with each image. The PyPI package page lists IMGKit 1.2.3, released February 23, 2023; verify compatibility with the wkhtmltoimage build deployed in your environment.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. It can capture one element by CSS selector, so you do not need to calculate pixel coordinates or maintain a custom isolated HTML copy. Before capture it accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.

One GET request returns PNG, JPEG, WebP, or PDF. The API also supports full-page capture with lazy images loaded, dark mode, device presets or custom viewports, retina scale, custom CSS and JavaScript, clicks, waits, hidden selectors, blocked resources, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen-TTL caching, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs, which can simplify migration.

Using the documented endpoint (see the ScreenshotNeo API docs):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo includes an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

Can I pass a CSS selector directly to IMGKit?

Not through a documented IMGKit or wkhtmltoimage option. Isolate the element in HTML or crop its rendered coordinates.

Why does the same crop change between machines?

Rendered coordinates depend on viewport width, responsive rules, margins, zoom, fonts, and image loading. Standardize those inputs or use an isolated document.

Which format should I use while debugging?

Use PNG: it preserves transparency and makes layout, clipping, and font problems easier to see.

Is there a published IMGKit crop benchmark?

No benchmark comparing IMGKit cropping with browser-native screenshot tools is established in the documented sources, so performance should be measured on your own pages.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.