Screenshot a Single Element to a File
Capture just one component, named by test and timestamp, ready for a visual comparison tool or a bug report.
Stable Verified against Selenium 4.48.0
Problem
A full-page screenshot contains too much noise for a visual comparison and too little context for a bug report. You want an image of one element, cropped to its bounds, saved with a meaningful name.
Solution
Scroll the element into view, wait for it to be stable, and use Selenium 4’s element-level screenshot.
Element screenshot with a stable name
Selenium 4 Stable
public static Path captureElement(WebDriver driver, By by, String name) throws IOException { WebElement el = new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.visibilityOfElementLocated(by)); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView({block: 'center'});", el);
Path dir = Files.createDirectories(Path.of("target", "screenshots")); String stamp = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").format(LocalDateTime.now()); Path out = dir.resolve(name + "-" + stamp + ".png"); Files.write(out, el.getScreenshotAs(OutputType.BYTES)); return out;}
Path shot = captureElement(driver, By.cssSelector("[data-testid='pricing-table']"), "pricing-table");from datetime import datetimefrom pathlib import Path
def capture_element(driver, locator, name): el = WebDriverWait(driver, 10).until(EC.visibility_of_element_located(locator)) driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", el)
out_dir = Path("screenshots"); out_dir.mkdir(exist_ok=True) out = out_dir / f"{name}-{datetime.now():%Y%m%d-%H%M%S}.png" el.screenshot(str(out)) return out
shot = capture_element(driver, (By.CSS_SELECTOR, "[data-testid='pricing-table']"), "pricing-table")const fs = require('fs');const path = require('path');
async function captureElement(driver, locator, name) {const el = await driver.wait(until.elementLocated(locator), 10000);await driver.wait(until.elementIsVisible(el), 10000);await driver.executeScript("arguments[0].scrollIntoView({block: 'center'});", el);
fs.mkdirSync('screenshots', { recursive: true });const stamp = new Date().toISOString().replace(/[:.]/g, '-');const out = path.join('screenshots', `${name}-${stamp}.png`);fs.writeFileSync(out, await el.takeScreenshot(), 'base64');return out;}public static string CaptureElement(IWebDriver driver, By by, string name){ var el = new WebDriverWait(driver, TimeSpan.FromSeconds(10)) .Until(d => { var e = d.FindElement(by); return e.Displayed ? e : null; }); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView({block: 'center'});", el);
Directory.CreateDirectory("screenshots"); var outPath = Path.Combine("screenshots", $"{name}-{DateTime.Now:yyyyMMdd-HHmmss}.png"); ((ITakesScreenshot)el).GetScreenshot().SaveAsFile(outPath); return outPath;}Why It Works
The W3C “Take Element Screenshot” command scrolls the element into view and crops the viewport capture to its bounding rectangle. Centring first avoids sticky headers intruding at the top of the crop.
Gotchas
- Elements taller than the viewport are cropped to the visible part in most browsers; resize the window or capture sections.
- Animations and hover states change pixels; wait for transitions to end and move the mouse away (
Actions.moveByOffset) before capturing. - For visual comparison, also fix the device pixel ratio and window size in the driver factory so baselines match across machines.
Learn the theory
- Screenshots and Videos Capture screenshots and record videos during test execution for debugging and reporting.
- AI-Assisted Selenium Testing Where AI genuinely helps a Selenium suite in 2026: generating page objects and tests, self-healing locators, visual assertions, triaging failures, and MCP-driven agents, plus the failure modes to avoid.