How can I capture screenshots of different parts of a webpage while scrolling using Playwright?


To capture screenshots of different parts of a webpage while scrolling using @playwright/test, you can combine the page.screenshot() and page.evaluate() methods. First, determine the height of the entire page using document.body.scrollHeight. Then, loop through each section by incrementing the scroll position and taking a screenshot at each position.

Here's an example:

const SCROLL_STEP = 500; // adjust this value to control how much to scroll at each step
const MAX_SCROLL_HEIGHT = await page.evaluate(() => document.body.scrollHeight);

let currentScrollHeight = 0;
while (currentScrollHeight < MAX_SCROLL_HEIGHT) {
  await page.evaluate(`window.scrollTo(0, ${currentScrollHeight})`);
  await page.waitForTimeout(100); // wait for some time for content to load

  const screenshotName = `screenshot-${currentScrollHeight}.png`;
  await page.screenshot({ path: screenshotName });

  currentScrollHeight += SCROLL_STEP;

In this example, we define two constants: SCROLL_STEP to control the scroll amount at each step (in pixels), and MAX_SCROLL_HEIGHT calculated using document.body.scrollHeight.

We use a while loop to scroll through the entire height of the web page. Inside the loop, we set the scroll position using page.evaluate(). We wait for a short time (using page.waitForTimeout()) for new content to load before taking a screenshot with page.screenshot(). Finally, we increment the current scroll height by our defined step size.

This code captures screenshots of every section of your web page as it scrolls down. You can adjust parameters such as scrolling speed or image quality according to your needs.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.