UI Screenshots

UI Screenshots

Teaches a coding agent to capture web app screenshots with Playwright and crop them with PIL, to document UI changes before and after.

Skill files1 file
SKILL.md203 lines
1
---
2
name: ui-screenshots
3
description: 'Capture screenshots of web apps during development using Playwright and PIL. Supports full-page captures, interactive states, and an iterate-on-crop workflow that avoids slow re-screenshots.'
4
---
5
6
# UI Screenshots
7
8
Capture screenshots of web apps and graphical UIs during development to document visual changes.
9
10
## When to Use This Skill
11
12
Use this skill when you need to:
13
14
- Capture the current state of a running web app
15
- Document a UI before and after a code change
16
- Screenshot interactive states (tooltips, hovers, selected elements)
17
- Capture specific sections of a page without re-screenshotting
18
19
## Prerequisites
20
21
```bash
22
pip install playwright Pillow -q
23
playwright install chromium
24
```
25
26
## Core Workflow
27
28
### 1. Take a raw full-page screenshot
29
30
```python
31
from playwright.async_api import async_playwright
32
33
async def capture(url="http://localhost:3000", out="screenshot-raw.png", width=1400, height=5000):
34
async with async_playwright() as p:
35
browser = await p.chromium.launch()
36
page = await browser.new_page(viewport={"width": width, "height": height})
37
await page.goto(url, wait_until="networkidle")
38
await page.wait_for_timeout(4000) # let charts/animations render
39
await page.screenshot(path=out, full_page=True)
40
await browser.close()
41
```
42
43
- Use a **tall viewport** (height=5000) so the page renders everything without scrolling
44
- `wait_until="networkidle"` + `wait_for_timeout(4000)` ensures async charts load
45
- `full_page=True` captures the entire scrollable content
46
47
### 2. View the raw image, then crop with PIL
48
49
**Do NOT try to get perfect crops via Playwright's `clip` parameter.** It's unreliable with full-page captures.
50
51
```python
52
from PIL import Image
53
54
img = Image.open("screenshot-raw.png")
55
cropped = img.crop((left, top, right, bottom)) # adjust based on what you see
56
cropped.save("screenshot-final.png")
57
```
58
59
1. Take the raw screenshot
60
2. View it to see actual pixel positions
61
3. Crop with PIL based on what you see
62
4. View the result — if not right, re-crop (instant, no re-screenshot needed)
63
64
### 3. Iterate on crop, not on capture
65
66
- Re-screenshotting is slow (browser launch + page load + render wait)
67
- Re-cropping is instant (just PIL)
68
- Get one good raw capture, then slice it as many ways as needed
69
70
### 4. Interactive states
71
72
```python
73
element = page.locator("selector").first
74
await element.hover()
75
await page.wait_for_timeout(1000) # let tooltip appear
76
await page.screenshot(path="screenshot-hover.png", full_page=True)
77
```
78
79
For "selected" state without hover effect, move the mouse away after clicking:
80
81
```python
82
await element.click()
83
await page.mouse.move(300, 300) # move away so hover doesn't show
84
await page.wait_for_timeout(500)
85
await page.screenshot(path="screenshot-selected.png", full_page=True)
86
```
87
88
### 5. Section-specific captures
89
90
Crop different sections from a single full-page screenshot:
91
92
```python
93
img.crop((0, 200, 920, 900)).save("screenshot-header.png")
94
img.crop((0, 900, 920, 1600)).save("screenshot-main.png")
95
```
96
97
## Guidelines
98
99
1. **Always capture before state BEFORE making any changes** — if you forget, you have to revert code to get a before shot
100
2. **Before/after pairs must use the same viewport width and crop** — otherwise the comparison is useless
101
3. **To get a "before" after you already changed code**: use `git checkout HEAD~1 -- <files>` to revert, screenshot, then `git checkout HEAD -- <files>` to restore
102
4. **For interactive states**: capture before AND after for each state — don't assume the "normal" before covers all cases
103
5. **Use `device_scale_factor=1`** in Playwright to force 1x pixels so screenshots match what users see at 100% zoom
104
6. **Charts need extra wait time** — Plotly, D3, etc. render asynchronously; 4s minimum after networkidle
105
7. **Narrow viewport reveals rendering bugs** — some border/alignment issues only appear at specific widths
106
107
## Non-Web App Screenshots
108
109
For desktop apps (VS, WPF, WinForms, console apps, terminals) where Playwright can't reach.
110
111
### mss + ctypes (recommended for desktop windows)
112
113
Find a window by title via Win32 API, capture its region with `mss`. Tested at ~33ms per capture.
114
115
```python
116
import ctypes
117
from ctypes import c_int, Structure, byref, windll
118
import mss
119
from PIL import Image
120
121
user32 = windll.user32
122
123
def find_window(title_contains):
124
"""Find visible windows matching a title substring."""
125
results = []
126
WNDENUMPROC = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
127
def cb(hwnd, _):
128
if user32.IsWindowVisible(hwnd):
129
buf = ctypes.create_unicode_buffer(256)
130
user32.GetWindowTextW(hwnd, buf, 256)
131
if title_contains.lower() in buf.value.lower():
132
results.append((hwnd, buf.value))
133
return True
134
user32.EnumWindows(WNDENUMPROC(cb), 0)
135
return results
136
137
def capture_window(title_contains, output_path):
138
"""Capture a window by title substring."""
139
windows = find_window(title_contains)
140
if not windows:
141
raise ValueError(f"No window matching '{title_contains}'")
142
hwnd = windows[0][0]
143
144
class RECT(Structure):
145
_fields_ = [('left', c_int), ('top', c_int), ('right', c_int), ('bottom', c_int)]
146
rect = RECT()
147
user32.GetWindowRect(hwnd, byref(rect))
148
w, h = rect.right - rect.left, rect.bottom - rect.top
149
150
with mss.mss() as sct:
151
shot = sct.grab({'left': rect.left, 'top': rect.top, 'width': w, 'height': h})
152
img = Image.frombytes('RGB', shot.size, shot.rgb)
153
img.save(output_path)
154
return img
155
156
# Usage:
157
capture_window('Visual Studio Code', 'vscode-capture.png')
158
```
159
160
**Prerequisites:** `pip install mss pillow`
161
**Limitation:** Window must be visible (not behind other windows or minimized).
162
163
### Electron apps (VS Code, etc.)
164
165
**Node.js Playwright only** — Python Playwright has no `electron` API. Captures via CDP (Chrome DevTools Protocol), not from the screen — works even while minimized.
166
167
```javascript
168
const { _electron: electron } = require('playwright');
169
const app = await electron.launch({
170
executablePath: 'C:\\Program Files\\Microsoft VS Code\\Code.exe',
171
args: ['--new-window', '--disable-extensions', '--user-data-dir=' + tmpDir]
172
});
173
const window = await app.firstWindow();
174
await window.waitForLoadState('domcontentloaded');
175
176
// Minimize immediately — captures still work via CDP
177
await app.evaluate(({ BrowserWindow }) => {
178
BrowserWindow.getAllWindows()[0].minimize();
179
});
180
181
await window.screenshot({ path: 'capture.png' }); // works while minimized!
182
await app.close();
183
```
184
185
**Critical**: `--user-data-dir=<temp>` is required or VS Code hands off to the existing instance and the launched process exits immediately.
186
187
### Decision tree
188
189
| Scenario | Tool | Notes |
190
|---|---|---|
191
| Web app (localhost) | Playwright | Proven, full DOM access |
192
| Electron app (VS Code) | Playwright Electron (Node.js) | Works minimized via CDP |
193
| Desktop app, visible window | mss + ctypes (find by title) | ~33ms per capture |
194
| Desktop app, behind windows | Windows Graphics Capture API | Complex setup, Win10 1903+ |
195
| Quick full-screen | mss | ~68ms |
196
197
## Limitations
198
199
- Web capture requires a locally running app or accessible URL
200
- Desktop capture (mss) requires the window to be visible and unobstructed
201
- Electron capture requires Node.js Playwright (not Python)
202
- Some SPAs with heavy client-side rendering may need custom wait logic beyond networkidle
203

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…