Selenium · Browser automation foundations
How do you capture screenshots for debugging and reports?
Short answer
Cast the driver to TakesScreenshot, call getScreenshotAs with FILE or BYTES, and attach the result to the report on failure. A screenshot shows the viewport, not the full page or the browser console.
Screenshots are most useful when captured automatically on failure, alongside the page URL, title and browser logs. Capturing on every step creates noise and slows the run. The WebDriver screenshot is the rendered viewport; full-page capture needs browser-specific tooling.
TakesScreenshot camera = (TakesScreenshot) driver;
byte[] png = camera.getScreenshotAs(OutputType.BYTES);
Path target = Paths.get("target/screenshots/failure.png");
Files.write(target, png);
File file = camera.getScreenshotAs(OutputType.FILE);
Files.copy(file.toPath(), target, StandardCopyOption.REPLACE_EXISTING);- Capture in a TestNG or JUnit listener on failure, not inside every test
- Include the current URL, title and timestamp in the attachment name
- Screenshots do not capture native dialogs, alerts or browser chrome
- Headless screenshots work, but rendering differences can matter for visual checks
- Browser console logs add context that a screenshot cannot show
- Full-page capture usually needs CDP or a third-party library, not plain WebDriver
A screenshot alone is weak evidence if the failure was an assertion on text. Attach the actual and expected values too. For intermittent failures, a screenshot of the final state may miss the transient overlay that caused the problem; pair it with a trace or video when available.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Where should screenshot capture live?
- 2What does a WebDriver screenshot not capture?
- 3How do you capture a full-page screenshot?
- 4What else should you attach with a failure screenshot?
Say it in the interview
I capture screenshots automatically on failure through a listener, using getScreenshotAs with BYTES so it can attach directly to the report. I include the URL, title and expected versus actual values, because a screenshot alone often lacks context. I know the WebDriver screenshot is only the viewport and does not include native dialogs. For intermittent failures I pair it with logs or a trace.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Selenium mock interview and get scored feedback on depth, clarity and confidence.