Take Screenshot in Playwright

Profile picture for user arilio666

In Playwright, we use the screenshot method to capture current view screenshots, full-page screenshots, and screenshots of a particular section or element.

Table of Content

  1. Screenshot of the current view
  2. Full Page Screenshot
  3. Screenshot of Section
  4. Element Screenshot
  5. Screenshot with the current timestamp
  6. Capture into Buffer
  7. API References
  8. Video Tutorial

Screenshot of the Current View

To capture the current view screenshot, use the below code.

test.only('capture screenshot', async ({ page }) => {
    await page.goto("https://www.programsbuzz.com/");
    await page.screenshot({ path: 'screenshots/screenshot.png');
 });

Here screenshots is the folder name, and screenshot.png is the file name.

Full Page Screenshot

To capture a screenshot of the full scrollable page, set the fullPage property value to true.

await page.screenshot({ path: 'screenshots/screenshot.png' , fullPage: true });

Setting the fullPage value to false will capture the current view screenshot, not the entire page.

The above code will capture a full-page screenshot of programsbuzz home page.

Screenshot of Section

To capture a screenshot of a section (e.g., footer section), find the selector of the section and use it as a locator:

await page.locator('.page-footer').screenshot({ path: 'screenshots/screenshot.png'})

The above code will capture a screenshot of programsbuzz footer section.

Element Screenshot

To capture a screenshot of the element, use the screenshot method with the element locator.

await page.locator("img[alt='Home']").screenshot({ path: 'screenshots/screenshot.png'});

The above code will capture a screenshot of programsbuzz logo.

Screenshot with the current timestamp

For making screenshots unique, add a timestamp using a date.now() method. The static date.now() method returns the number of milliseconds elapsed since January 1, 1970.

await page.locator("img[alt='Home']").screenshot({ path: 'screenshots/screenshot_'+Date.now()+'.png'});

Capture into Buffer

Sometimes, you will need a screenshot in base64 format for different reports or servers.

const buffer = await page.screenshot();
console.log(buffer.toString('base64'));

API References

Screenshots API accepts many parameters for image format, clip area, quality, etc. Check Below APIs for that.

Video Tutorial: Playwright Screenshot