In this example we will explore how to capture different types of screenshots using Playwright, with practical code examples. To capture a screenshot in Playwright, you can use the page.screenshot() method.
Taking a Viewport-Only Screenshot
To capture a screenshot of the visible part of a page, you can use the following code snippet:
// @ts-check import { test, expect } from '@playwright/test'; import { chromium } from 'playwright'; test('capture page screenshot', async({page}) =>{ // Navigate to web page. await page.goto('http://www.skptricks.com'); //capture screenshot await page.screenshot({ path: "tests/screenshots/" + Date.now() + "pageScreenshot.png", }); });
Taking a Full-Page Screenshot
If you need to capture the entire content of a webpage, including parts that are not currently visible on the screen, you can use the fullPage option:
// @ts-check import { test, expect } from '@playwright/test'; import { chromium } from 'playwright'; test('capture full page screenshot', async({page}) =>{ // Navigate to web page. await page.goto('http://www.skptricks.com'); //capture full page screenshot await page.screenshot({ path: "tests/screenshots/" + Date.now() + "pageScreenshot.png", fullPage: true, }); });
Taking specific element Screenshot
Sometimes, you may only want to capture a specific element on the page. Playwright makes this easy with element handles:
// @ts-check import { test, expect } from '@playwright/test'; import { chromium } from 'playwright'; test('capture particular element screenshot', async({page}) =>{ // Navigate to web page. await page.goto('http://www.skptricks.com'); //capture particular element screenshot await page.locator('(//*[@class="post-outer"])[1]').screenshot({ path: "tests/screenshots/" + Date.now() + "pageScreenshot.png", fullPage: true, }); });
Taking screenshots in Playwright is straightforward and provides flexibility depending on your testing needs. Whether you need to capture an entire page or just a specific element, Playwright has you covered.
No comments:
Post a Comment