Skip to content
CodeKruPro

Save a screenshot of the viewport

Automation taskEasy-MediumAsked in: Capgemini, Infosys, TCS, Wipro

Interviewers ask: "How do you take a screenshot in Selenium?" and then "How do you attach it to a failed test?" Start with a screenshot of the viewport (the visible part of the page) and check that the saved file exists and is not empty.

Take Viewport Screenshot

Take Viewport Screenshot

Selenium can capture screenshots using the TakesScreenshot interface. getScreenshotAs(OutputType.FILE) saves the image as a PNG file. In Chrome it captures the visible viewport, the part of the page that fits in the window, not the whole scrolling page.

Task:

  1. Navigate to https://testkru.com/Elements/Buttons
  2. Take a screenshot of the viewport as a File
  3. Print whether the file exists, after the label Screenshot taken:
  4. Print whether its size in bytes is greater than 0, after the label File has content:

Expected output:

Screenshot taken: true
File has content: true