On this page
By default page.screenshot() captures only what fits in the window. This post covers the rest: the whole page, one element, PDFs, other screen sizes, waiting until the content has loaded, and many pages at once.
Setup
Playwright 1.65 needs Python 3.10 or newer.
pip install playwright
playwright install chromium
Basic screenshot
What’s visible in the viewport:
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto('https://example.com')
await page.screenshot(path='screenshot.png')
await browser.close()
asyncio.run(main())
The default viewport is 1280×720, so that is the size of the image.
Full-page screenshot
With full_page=True you get the whole scrollable page in one tall image:
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto('https://example.com')
await page.screenshot(path='full-page.png', full_page=True)
await browser.close()
asyncio.run(main())
Playwright doesn’t scroll to take it, though. Images that load lazily when you scroll to them may show up as empty boxes. Scroll the page first (for example with page.mouse.wheel() in a loop) if the bottom half matters.
Viewport size
The width of the viewport decides which layout the site uses. To capture desktop and mobile versions:
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
# Desktop
page = await browser.new_page(viewport={'width': 1920, 'height': 1080})
await page.goto('https://example.com')
await page.screenshot(path='desktop.png', full_page=True)
# Mobile
page_mobile = await browser.new_page(viewport={'width': 390, 'height': 844})
await page_mobile.goto('https://example.com')
await page_mobile.screenshot(path='mobile.png', full_page=True)
await browser.close()
asyncio.run(main())
A narrow viewport alone doesn’t make the browser a phone. Sites that detect mobile by User-Agent or touch support still serve the desktop version. For that, use one of Playwright’s device presets: browser.new_context(**p.devices['iPhone 13']).
One element
Call .screenshot() on a locator to capture just that element:
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto('https://example.com/pricing')
# Screenshot just the pricing table
pricing_table = page.locator('.pricing-table')
await pricing_table.wait_for()
await pricing_table.screenshot(path='pricing.png')
await browser.close()
asyncio.run(main())
In visual regression tests this keeps the comparison to the component you changed, so an edit elsewhere on the page doesn’t fail the test.
JPEG instead of PNG
await page.screenshot(
path='screenshot.jpg',
type='jpeg',
quality=85, # 0-100, higher = better quality + larger file
full_page=True
)
JPEG isn’t always smaller. Full-page shots at 1440 px wide in December 2026:
| Page | PNG | JPEG, quality 85 |
|---|---|---|
| playwright.dev | 659 KB | 354 KB |
| github.com | 638 KB | 767 KB |
| Wikipedia article “Web scraping” | 2,319 KB | 2,132 KB |
Pages made of flat colors and text compress well as PNG. JPEG wins on photos and gradients. Check a few of your own pages before you pick.
Screenshot as bytes
Without path, screenshot() returns the image as bytes, which is handy for a database or an API:
import asyncio
import base64
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto('https://example.com')
# Returns bytes directly
screenshot_bytes = await page.screenshot(full_page=True)
# Example: encode as base64 for an API
encoded = base64.b64encode(screenshot_bytes).decode('utf-8')
print(f'Screenshot size: {len(screenshot_bytes)} bytes')
await browser.close()
asyncio.run(main())
Waiting for content
goto() returns when the load event fires. Content that scripts fetch afterwards may still be missing, so on dynamic pages a screenshot taken right away can catch them half-drawn.
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto('https://example.com/dashboard')
# Option 1: wait for network to go idle (no requests for 500ms)
await page.wait_for_load_state('networkidle')
# Option 2: wait for a specific element to appear
await page.locator('.dashboard-chart').wait_for()
# Option 3: wait a fixed amount of time (last resort)
await page.wait_for_timeout(2000)
await page.screenshot(path='dashboard.png', full_page=True)
await browser.close()
asyncio.run(main())
Waiting for the element you need is the most reliable of the three. Playwright’s documentation advises against networkidle in tests: pages with analytics, polling or open connections may never go quiet, and the wait times out. A fixed pause is a guess, and either too long or too short.
page.pdf() exists only in Chromium; Firefox and WebKit don’t have it.
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto('https://example.com/report')
await page.wait_for_load_state('networkidle')
await page.pdf(
path='report.pdf',
format='A4',
print_background=True, # include background colors and images
margin={'top': '20px', 'bottom': '20px', 'left': '20px', 'right': '20px'}
)
await browser.close()
asyncio.run(main())
Without print_background=True the PDF drops background colors and images, the same as printing from a browser with that option off.
Many pages in parallel
Each URL gets its own context, and asyncio.gather() runs them at the same time:
import asyncio
import os
from playwright.async_api import async_playwright
URLS = [
'https://example.com',
'https://example.org',
'https://example.net',
'https://playwright.dev',
'https://github.com',
]
SAVE_DIR = './screenshots'
os.makedirs(SAVE_DIR, exist_ok=True)
async def screenshot_page(browser, url: str, index: int):
context = await browser.new_context(viewport={'width': 1440, 'height': 900})
page = await context.new_page()
try:
await page.goto(url, timeout=30000)
await page.wait_for_load_state('networkidle')
filename = f'page_{index:03d}.png'
await page.screenshot(
path=os.path.join(SAVE_DIR, filename),
full_page=True
)
print(f'[{index}] Saved: {filename} ({url})')
except Exception as e:
print(f'[{index}] Failed: {url}: {e}')
finally:
await context.close()
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
tasks = [screenshot_page(browser, url, i) for i, url in enumerate(URLS)]
await asyncio.gather(*tasks)
await browser.close()
asyncio.run(main())
Contexts don’t share cookies or storage, so one page can’t affect another. For a list of hundreds of URLs, don’t start them all at once: every open page takes memory. Wrap screenshot_page in an asyncio.Semaphore(10) or similar to cap how many run together.
Example: watching a page for changes
A daily screenshot of a competitor’s pricing page, compared with yesterday’s:
import asyncio
import os
import hashlib
from datetime import date
from playwright.async_api import async_playwright
MONITOR_URLS = {
'competitor_pricing': 'https://competitor.com/pricing',
'competitor_homepage': 'https://competitor.com',
}
SAVE_DIR = './monitoring'
os.makedirs(SAVE_DIR, exist_ok=True)
async def capture_and_compare(page, name: str, url: str):
await page.goto(url)
await page.wait_for_load_state('networkidle')
screenshot_bytes = await page.screenshot(full_page=True)
today = date.today().isoformat()
today_path = os.path.join(SAVE_DIR, f'{name}_{today}.png')
with open(today_path, 'wb') as f:
f.write(screenshot_bytes)
# Check if content changed vs yesterday
today_hash = hashlib.md5(screenshot_bytes).hexdigest()
yesterday = str(date.fromordinal(date.today().toordinal() - 1).isoformat())
yesterday_path = os.path.join(SAVE_DIR, f'{name}_{yesterday}.png')
if os.path.exists(yesterday_path):
with open(yesterday_path, 'rb') as f:
yesterday_hash = hashlib.md5(f.read()).hexdigest()
if today_hash != yesterday_hash:
print(f'CHANGED: {name} ({url})')
else:
print(f'No change: {name}')
else:
print(f'First capture: {name}')
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page(viewport={'width': 1440, 'height': 900})
for name, url in MONITOR_URLS.items():
await capture_and_compare(page, name, url)
await browser.close()
asyncio.run(main())
Run it from cron once a day. The hash only says that something changed, not what. It also reacts to a rotating banner, a new date in the footer or an animation caught at a different frame, so expect false alarms on busy pages. Comparing the text of one element, such as the price table, is often more useful than comparing whole images.
Common problems
The screenshot stops at the bottom of the window. Add full_page=True.
The page looks different from your own browser. The viewport differs, or the site treats headless browsers differently. Set the viewport to your screen size first. If it still differs, the site is probably detecting automation; see Playwright stealth mode.
Parts of the page are empty. Wait for the element you need with page.locator('.element').wait_for(). For lazy images below the fold, scroll down before the screenshot.
The PDF has no backgrounds. Add print_background=True to page.pdf().
Text looks blurry on a high-DPI screen. Create the context with device_scale_factor=2. The image comes out at twice the width and height.