Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Playwright Python: Screenshot Lazy-Loaded Pages

· 5 min read · Home Tech

In this article
  1. Why Lazy Loading Breaks Screenshots
  2. Basic Scrolling with Playwright
  3. Handling Dynamic Content and Infinite Scroll
  4. Waiting for Images to Load
  5. Viewport Screenshots vs Full-Page
  6. Common Pitfalls and Solutions
  7. Frequently Asked Questions
  8. Alternatives and Advanced Techniques

To capture screenshots of lazy-loaded pages with Playwright in Python, you must scroll through the page to trigger content loading before taking the screenshot. This article explains how to implement scrolling, handle timing, and capture full-page or viewport screenshots reliably.

Why Lazy Loading Breaks Screenshots

Lazy loading is a technique where images, iframes, or other content are only loaded when they scroll into the viewport. If you take a screenshot immediately after page load, the off-screen content may be missing or displayed as placeholders. This is especially common on infinite-scroll feeds, image galleries, and long-form articles with embedded media.

The core problem is that Playwright's page.screenshot() captures the current DOM state. If the browser hasn't fetched the off-screen resources, they simply won't appear in the image. You need to force the browser to load them by scrolling.

Basic Scrolling with Playwright

Playwright provides a mouse.wheel() method and element.scroll_into_view_if_needed(). For a full-page capture, you need to scroll through the entire document. A common approach is to use JavaScript to set window.scrollTo() in a loop, waiting a short time between steps.

import asyncio
from playwright.async_api import async_playwright

async def capture_full_page(url, output_path):
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto(url, wait_until="networkidle")
        
        # Scroll to bottom to trigger lazy loading
        await page.evaluate("""
            async () => {
                await new Promise((resolve) => {
                    let totalHeight = 0;
                    const distance = 100;
                    const timer = setInterval(() => {
                        const scrollHeight = document.body.scrollHeight;
                        window.scrollBy(0, distance);
                        totalHeight += distance;
                        if (totalHeight >= scrollHeight) {
                            clearInterval(timer);
                            resolve();
                        }
                    }, 100);
                });
            }
        """)
        
        await page.screenshot(path=output_path, full_page=True)
        await browser.close()

This script scrolls down in 100-pixel steps, waiting 100ms between each step. After reaching the bottom, it takes a full-page screenshot. The full_page=True option captures the entire scrollable area, not just the viewport.

Handling Dynamic Content and Infinite Scroll

Infinite scroll pages load new content as you approach the bottom. A single scroll-to-bottom pass may not be enough. You need to repeat the scroll until the page height stops increasing. Here's a more robust approach:

async def scroll_until_stable(page, max_attempts=10):
    previous_height = await page.evaluate("document.body.scrollHeight")
    for _ in range(max_attempts):
        await page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
        await page.wait_for_timeout(1000)  # wait for content to load
        new_height = await page.evaluate("document.body.scrollHeight")
        if new_height == previous_height:
            break
        previous_height = new_height

This function scrolls to the bottom, waits, and checks if the page height changed. If it didn't, the page is stable. Adjust the max_attempts and timeout based on the site's behavior.

Waiting for Images to Load

Scrolling alone doesn't guarantee images are fully fetched. You should wait for all images to be complete. Playwright's page.wait_for_load_state("networkidle") is a good start, but it may not cover images that load after scrolling. A more reliable method is to wait for all img elements to have complete set to true:

await page.wait_for_function("""
    () => {
        const images = Array.from(document.images);
        return images.length > 0 && images.every(img => img.complete);
    }
""")

Note that some images may fail to load (404 errors), so you might want to check img.naturalWidth instead. A failed image has naturalWidth of 0.

Viewport Screenshots vs Full-Page

Sometimes you only need a screenshot of the visible viewport after scrolling to a specific element. Use element.scroll_into_view_if_needed() to bring the element into view, then call page.screenshot() without full_page.

element = await page.query_selector("#target")
await element.scroll_into_view_if_needed()
await page.screenshot(path="viewport.png")

This is useful for capturing a specific section of a page, like a product card or a chart. For full-page captures, the scrolling method is essential.

Common Pitfalls and Solutions

  • Missing images after scrolling: Use wait_for_function to ensure all images are loaded.
  • Stale elements: If the page re-renders, your references may become invalid. Re-query elements after scrolling.
  • Scroll height not changing: Some sites load content on click or hover, not scroll. You may need to simulate those interactions.
  • Performance: Scrolling too fast may cause the browser to skip loading. Use a slower scroll speed or longer waits.
  • Headless mode: In headless browsers, lazy loading may behave differently. Test with headless=False to debug.

Frequently Asked Questions

Why does my screenshot show blank spaces where images should be?

Blank spaces usually mean the images haven't loaded yet. Your scroll script may not have waited long enough for the network requests to complete. Increase the wait time after scrolling, or use wait_for_function to check that all images are complete.

Can I use Playwright's built-in full_page without scrolling?

No. full_page=True only captures the current scrollable area. If content hasn't been loaded, it won't appear. You must scroll first to trigger lazy loading.

What is the best scroll step size and delay?

There's no universal best. A step of 100-200 pixels with a delay of 50-200ms works for most sites. For heavy pages, use larger delays. Experiment with your target site to find the sweet spot.

How do I handle pages that load content on click?

You need to identify the clickable elements (like "Load More" buttons) and click them in a loop until no more appear. Use page.click() and check for the element's visibility.

Does Playwright wait for lazy-loaded images if I use wait_until="networkidle"?

No. networkidle waits for the network to be idle for 500ms, but lazy-loaded images are not requested until you scroll. After scrolling, you need to wait again, or use the wait_for_function approach.

Can I take a screenshot of a specific element after lazy loading?

Yes. After scrolling to the element, use element.screenshot() to capture just that element. This is more efficient than a full-page screenshot if you only need a small part.

Alternatives and Advanced Techniques

For very complex pages, consider using Playwright's page.locator to scroll to each element individually. You can also use page.keyboard.press("End") to jump to the bottom, but this may not trigger all lazy loaders. Another approach is to use page.route to intercept requests and wait for specific ones. However, the scrolling method is the most straightforward and works for the majority of cases.

If you need to capture a screenshot of a page that requires login, you'll need to handle authentication first. Playwright supports persistent contexts, so you can save the login state and reuse it.