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

To screenshot part of an iframe with Selenium, switch WebDriver into the iframe, find the element you want, and call that element’s screenshot() method. The frame switch matters: WebDriver searches the current browsing context, so it cannot locate an element inside a frame while it is still operating in the parent document.

Capture one element inside an iframe with Python

This is the direct approach when you want a particular element, such as a chart or report panel, rather than the whole browser window. Find the iframe in the current document first; switch into it; then locate and capture the target element.

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
try:
    driver.get("https://example.test/page")

    frame = driver.find_element(By.CSS_SELECTOR, "iframe#report")
    driver.switch_to.frame(frame)

    target = driver.find_element(By.CSS_SELECTOR, "#chart")
    target.screenshot("chart.png")
finally:
    driver.switch_to.default_content()
    driver.quit()

Replace the example address and selectors with those for your page. The selector iframe#report identifies the frame element in the parent page; #chart is looked up only after the context changes, so it must identify an element inside that iframe. The resulting PNG is saved to the path passed to screenshot().

Why the order matters

  1. Load the page containing the iframe.
  2. Locate the iframe element while WebDriver is in the top-level document.
  3. Call driver.switch_to.frame(frame) to make the iframe’s document the current context.
  4. Find the desired content inside that context and call its screenshot() method.

The frame element is a container for another document, not the content document itself. Trying to find #chart before switching asks Selenium to find it in the parent page, where it may not exist.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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

Choose a stable way to identify the frame

switch_to.frame() accepts a frame index, a frame name, or an iframe WebElement. Passing the WebElement found with a CSS selector makes the relationship between the page markup and the switch explicit. An index can be convenient when the page is fixed, but it depends on frame ordering; if that ordering changes, the same index may refer to a different frame. A name is another option when the page has a reliable frame name.

What the element screenshot includes

A WebElement can capture its own screenshot, which is usually the simplest way to make a partial capture. Selenium’s Java TakesScreenshot interface describes element captures as covering the element’s entire content or its visible portion, depending on the implementation. That distinction matters for elements larger than the area currently visible in the browser: do not assume every browser and driver will produce the same result for off-screen or oversized content.

If the result is clipped or differs from what you expect, first confirm that the selector identifies the intended element and that the element is displayed as expected in the test browser. If you specifically need a crop from the current window rather than an element-level capture, use the full-window fallback below and verify its crop coordinates against the browser configuration used by your suite.

Switch back out of the frame safely

After a frame switch, WebDriver remains in that frame until you change context again. Use parent_frame() to move up one level, or default_content() to return directly to the top-level document. The Python example uses default_content() in its cleanup so the context is reset even if locating the target or saving its screenshot raises an error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • 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

Resetting is important when later test steps need to interact with the parent page. Otherwise, a locator for a parent-page button will be searched for inside the iframe and will not be found there.

Handle nested iframes one level at a time

If the target is inside an iframe that is itself inside another iframe, switch through the frames in order. At each level, locate the next iframe from the current context, switch into it, and continue until you reach the document containing the target.

outer_frame = driver.find_element(By.CSS_SELECTOR, "iframe#outer")
driver.switch_to.frame(outer_frame)

inner_frame = driver.find_element(By.CSS_SELECTOR, "iframe#inner")
driver.switch_to.frame(inner_frame)

target = driver.find_element(By.CSS_SELECTOR, "#chart")
target.screenshot("chart.png")

driver.switch_to.parent_frame()
driver.switch_to.parent_frame()

Each parent_frame() call moves up one level. Call it once for every switch you need to unwind. If the next operation should return to the top-level page regardless of nesting depth, use default_content() instead. Keep the frame-selection order and the unwinding order clear; a nested frame is not located from the top-level document unless you first switch into its containing frame.

Use a full-window screenshot and crop it as a fallback

If direct element capture is unavailable in your setup, take a screenshot of the current browser window and crop the image afterward. Selenium’s get_screenshot_as_png() returns PNG bytes for the current window. The example uses Pillow to open those bytes and save a rectangular crop:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • 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.
from io import BytesIO
from PIL import Image

png = driver.get_screenshot_as_png()
image = Image.open(BytesIO(png))
box = (left, top, left + width, top + height)
image.crop(box).save("partial.png")

Install Pillow in the Python environment that runs the test if it is not already available. Replace left, top, width, and height with numeric crop values. The box is expressed as the left, upper, right, and lower edges of the crop; calculate the right and lower edges by adding the crop width and height to the origin.

The crop coordinates must match the screenshot’s coordinate system and pixel scale. Derive and verify them for the same viewport and display configuration used to take the screenshot. A crop positioned using coordinates from a different browser size or scale can cut off the target or include the wrong region. This approach also captures the window first, so it is less direct when all you need is one WebElement.

save_screenshot("page.png") is another whole-window option when you want Selenium to write the PNG file directly. Use an element screenshot for a target element; use a window capture plus crop when you need to define the partial area by coordinates or when element capture is unavailable.

Capture an iframe element with Java

The same context sequence works in Java: locate the iframe, switch into it, locate the target, and request a screenshot from the target WebElement. The Java Selenium API exposes this through TakesScreenshot on WebElement implementations.

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.
Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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
WebElement frame = driver.findElement(By.cssSelector("iframe#report"));
driver.switchTo().frame(frame);

WebElement target = driver.findElement(By.cssSelector("#chart"));
File file = target.getScreenshotAs(OutputType.FILE);

driver.switchTo().defaultContent();

This snippet assumes driver has already been created and the page has been loaded. As in Python, the frame selector is resolved in the parent document and the target selector is resolved after switching. In a test that can fail between the switch and reset, put the reset and driver cleanup in the test’s cleanup mechanism so later work does not accidentally remain in the iframe.

Or skip the browser setup

If you need a screenshot of a webpage rather than a Selenium-controlled element workflow, ScreenshotNeo offers a screenshot API. Its one-request cURL example is:

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

See the ScreenshotNeo API documentation for request options. ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response includes X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Selenium remains the direct choice when the job specifically requires switching into a frame and capturing a selected element in an automated browser test.

Sign up for ScreenshotNeo’s free plan and get 1,000 screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common capture problems

The target element cannot be found

Check which document WebDriver is currently using. Locate the iframe from its parent context, switch into it, and only then search for the target. If the iframe is nested, switch into each containing frame before locating the next iframe. Also verify that the selectors match the actual page and frame markup.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【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.

A later locator cannot find a parent-page element

WebDriver may still be operating inside the iframe. Call parent_frame() to move up one level or default_content() to reset to the top document before searching for parent-page content.

The saved image is not the expected partial area

Confirm that the selected WebElement is the element you intended to capture. Element capture may represent the visible portion or entire content depending on implementation. If you use a window screenshot and crop, verify that the crop coordinates and pixel scale correspond to the same browser viewport and display configuration used for the screenshot.

The nested-frame target is still inaccessible

Check the nesting sequence rather than trying to select the inner frame from the top-level document. Switch into its containing iframe first, then locate and switch into the nested iframe. When finished, unwind one level at a time or reset all the way with default_content().

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

The capture works, but the test remains in the wrong context after an error

Put context cleanup in a finally block or the equivalent test cleanup path. A failed locator or screenshot call should not leave later steps searching in a frame unintentionally. The Python example resets the context and quits the driver in finally.

Choose the right capture method

Need Method What to account for
Screenshot of one element in an iframe Switch to the iframe, then call the WebElement screenshot method. The element capture can represent visible or entire content depending on implementation.
Screenshot of an area defined by pixel coordinates Capture the current window and crop the PNG. Crop coordinates must match the screenshot viewport and pixel scale.
Target inside nested iframes Switch through each containing iframe before locating the target. Return with one parent_frame() per level, or reset with default_content().

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.