Guide ·
Screenshot to Code: Turn a Web Page into HTML with Claude or GPT (Python)
Vision models are good at turning a picture of a page into HTML. Most guides start from a screenshot you already have. When you start from a live page, the capture is where the result is decided: a 1280 × 6000 full-page screenshot reaches Claude 4.7 and later about 549 pixels wide and older Claude models about 334 pixels wide, and no model can read body text at that size. This guide builds the whole pipeline in one Python script: capture, slice, generate, render the result, fix the differences.

Short answer
- Capture the page at 1280 px wide, full page, with cookie banners and ads blocked, and ask for the page text in the same call.
- Cut the screenshot into slices about 900 px tall. Each slice then fits every current Claude and GPT model without being shrunk.
- Send the slices in order, plus the page text, and ask for one self-contained HTML file.
- Render that file, show the model both versions and ask it to fix the differences. The script caps this at two passes.
The full script is in step 2. It needs a SnapshotFlow API key and an Anthropic or OpenAI key, and it also accepts a PNG you already have.
Three ways to do it
| Approach | What you do | Good for | Trade-off |
|---|---|---|---|
The open-source app (abi/screenshot-to-code) | Run it locally with Docker, add model keys, upload a screenshot, mockup or screen recording | Trying it out by hand, picking a stack (HTML + Tailwind, React, Vue, Bootstrap, Ionic) | An interactive app, not a step in your own pipeline |
| Your own script | Capture the URL, call the model API, save the file | Batch jobs, migrations, CI, custom prompts and output formats | You run one Python script of about 150 lines, shown below |
| A coding agent with a screenshot tool | Ask Claude Code, Cursor or another MCP client to rebuild the page | Rebuilding inside an existing codebase with its components and styles | Less control over each step; the agent decides when to capture |
The open-source screenshot-to-code project is where the term comes from. It has over 81,000 GitHub stars, an MIT license, and support for OpenAI, Anthropic and Gemini models. Its README recommends Gemini for the best accuracy. It also has a preview tool that renders the generated page in a headless browser so the model can check its own work. That render-and-check idea is step 3 of this guide.
The rest of this guide covers the second option, because it is the one you can run on a hundred URLs, put in a job queue, or point at your own design system.
Why one tall screenshot fails
Every vision API resizes large images before the model sees them. The limit is on the long edge and on the number of image tokens, and a full-page screenshot breaks both: it is narrow and very tall, so shrinking it to fit the height shrinks the width with it.
We ran common capture sizes through the resize rules in the Claude and OpenAI vision docs. Claude uses a 1,568 px long edge on older models and 2,576 px on Claude 4.7 and later. GPT-5.5 at detail: "high" uses a 2,048 px limit and 2,500 patches of 32 px.
| What you send | Claude, standard tier | Claude 4.7+, high-res tier | GPT-5.5, high |
|---|---|---|---|
| Viewport, 1280 × 800 | 1280 × 800 | 1280 × 800 | 1280 × 800 |
| Full page, 1280 × 6000 | about 334 × 1568 | about 549 × 2576 | about 436 × 2048 |
| Full page, 1280 × 12000 | about 167 × 1568 | about 274 × 2576 | about 218 × 2048 |
| Retina viewport, 2560 × 1600 | about 1390 × 868 | about 2410 × 1506 | about 1997 × 1248 |
| One slice, 1280 × 900 | 1280 × 900 (≈1,518 tokens) | 1280 × 900 | 1280 × 900 |
At 334 px wide, 16 px body text becomes about 4 px tall. The model still sees the layout, so it guesses the structure right and invents the words. That is the usual "it looks similar but every heading is different" result.
A 1280 × 900 slice passes every limit in the table unchanged: on Claude's standard tier it costs about 1,518 tokens, just under the 1,568-token cap, so a taller slice would already be shrunk there. A 6,000 px page becomes seven slices and roughly 10,000 image tokens, and every slice keeps full detail.
Real pages are often longer than 6,000 px. We captured the snapshotflow.com home page with the settings from step 1: the full page came back 1265 × 10281 px (the scrollbar takes 15 px of the 1280 px viewport). By Anthropic's limits, Claude 4.7 and later see it at about 317 × 2576 and older Claude models at about 193 × 1568. The script below cuts the same capture into 12 slices instead.

The retina row shows the other common mistake. device_scale_factor=2 doubles every dimension, and the API shrinks most of it back. For screenshot to code, capture at a scale factor of 1.
Step 1: capture the page
One call to the SnapshotFlow /screenshot endpoint returns a signed link to the image and the page text:
curl --get "https://api.snapshotflow.com/screenshot" \
-H "X-Api-Key: $SNAPSHOTFLOW_API_KEY" \
--data-urlencode "url=https://example.com" \
--data-urlencode "width=1280" \
--data-urlencode "full_page=true" \
--data-urlencode "format=jpeg" \
--data-urlencode "quality=85" \
--data-urlencode "block_cookie_banners=true" \
--data-urlencode "block_ads=true" \
--data-urlencode "extract_content=true" \
--data-urlencode "content_format=markdown" \
--data-urlencode "response_type=json" \
-o capture.json
| Parameter | Why it matters here |
|---|---|
width=1280 | A common desktop width. It sets the breakpoint the model will copy, so match it to the layout you want. |
full_page=true | Captures the whole scrollable height. Slicing happens on your side, so it is still one capture. |
block_cookie_banners, block_ads | Without them the model rebuilds the consent banner as part of the page. |
extract_content=true | Adds the page text as Markdown in the content field. The model copies wording from it instead of reading pixels. |
format=jpeg | Much smaller than PNG for photos and gradients. PNG is better for flat UI with thin lines. |
wait_for_selector | Add it for single-page apps so you do not capture a loading skeleton. |
hide_selectors | Hides chat widgets and other overlays you do not want rebuilt. |
For the mobile layout, run a second capture with width=390&viewport_mobile=true and send both sets of slices. The model can then write the media queries instead of guessing them.
Step 2: generate HTML with Claude
This is the whole pipeline in one file: capture, slice, generate, then two render-and-fix passes, saving index.html after every step. Install the dependencies with pip install requests pillow anthropic, set SNAPSHOTFLOW_API_KEY and ANTHROPIC_API_KEY, and run python screenshot_to_code.py https://example.com:
# screenshot_to_code.py
import base64, io, os, re, sys
import anthropic
import requests
from PIL import Image
SNAP = "https://api.snapshotflow.com/screenshot"
SNAP_HEADERS = {"X-Api-Key": os.environ["SNAPSHOTFLOW_API_KEY"]}
MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5-5")
WIDTH = 1280
SLICE_HEIGHT = 900 # fits every current Claude and GPT model without resizing
FIX_PASSES = 2
client = anthropic.Anthropic()
# --- SnapshotFlow -----------------------------------------------------------
def snapshot(**params):
"""One capture: returns (PIL image, page text or "")."""
r = requests.get(SNAP, headers=SNAP_HEADERS, timeout=120, params={
"width": WIDTH, "full_page": "true", "format": "jpeg", "quality": 85,
"response_type": "json", **params,
})
r.raise_for_status()
data = r.json()
file = requests.get(data["storagePath"], timeout=120) # signed URL, valid 1 hour
file.raise_for_status()
image = Image.open(io.BytesIO(file.content)).convert("RGB")
return image, data.get("content") or ""
def load(source):
"""A URL is captured with its page text; a local PNG or JPEG is used as is."""
if os.path.exists(source):
image = Image.open(source).convert("RGB")
if image.width > WIDTH: # a retina screenshot: scale back to 1x
image = image.resize((WIDTH, round(image.height * WIDTH / image.width)))
return image, ""
return snapshot(url=source, block_cookie_banners="true", block_ads="true",
extract_content="true", content_format="markdown")
def render(html):
"""Screenshot the generated HTML with the same width as the original."""
encoded = base64.urlsafe_b64encode(html.encode()).decode().rstrip("=")
if len(encoded) <= 12_000: # about 9 KB of HTML fits in the query string
return snapshot(html=encoded)[0]
preview = os.environ.get("PREVIEW_URL")
if not preview:
return None
input(f"index.html is too long for the html parameter. "
f"Upload it to {preview} and press Enter... ")
return snapshot(url=preview, cache="false")[0]
# --- Model (Claude) ---------------------------------------------------------
def text_block(text):
return {"type": "text", "text": text}
def image_block(jpeg_bytes):
return {"type": "image", "source": {
"type": "base64", "media_type": "image/jpeg",
"data": base64.b64encode(jpeg_bytes).decode()}}
def ask(content):
message = client.messages.create(
model=MODEL, max_tokens=16000,
messages=[{"role": "user", "content": content}],
)
return "".join(b.text for b in message.content if b.type == "text")
# --- Pipeline ---------------------------------------------------------------
def slices(image, label):
"""Cut a tall screenshot into 900 px slices, top to bottom."""
blocks = []
for top in range(0, image.height, SLICE_HEIGHT):
part = image.crop((0, top, image.width, min(top + SLICE_HEIGHT, image.height)))
buf = io.BytesIO()
part.save(buf, "JPEG", quality=85)
blocks.append(text_block(f"{label}, y = {top} px:"))
blocks.append(image_block(buf.getvalue()))
return blocks
def extract_html(answer):
fenced = re.search(r"```(?:html)?\s*(.*?)```", answer, re.S)
return (fenced.group(1) if fenced else answer).strip()
def save(html, step):
with open("index.html", "w", encoding="utf-8") as f:
f.write(html)
print(f"index.html saved after {step}: {len(html):,} characters")
RULES = """
- Plain HTML and CSS in one file. No JavaScript, frameworks or external files.
- Use the exact wording from <page_text>. If it is empty, copy the text
from the images. Do not invent copy.
- Match layout, spacing, colors and font sizes as closely as you can.
- For photos and illustrations, use a <div> with the right size and a
neutral background and add a comment describing the image.
- Use semantic elements (header, nav, main, section, footer)."""
PROMPT = f"""The images above are consecutive slices of one web page, top to bottom,
captured at 1280 px wide. Rebuild the page as a single index.html file.
Rules:{RULES}
Return only the HTML."""
FIX_PROMPT = f"""The first set of slices is the original page. The second set is a
render of your HTML above. List the visible differences in layout, spacing,
sizes, colors and order, then return the full corrected index.html.
Rules:{RULES}
End your answer with the HTML in one code block."""
def main(source):
original, page_text = load(source)
page_text = f"<page_text>\n{page_text[:30000]}\n</page_text>"
html = extract_html(ask(slices(original, "Original page")
+ [text_block(f"{page_text}\n\n{PROMPT}")]))
save(html, "the first draft")
for n in range(1, FIX_PASSES + 1):
rendered = render(html)
if rendered is None:
print("Skipping the fix passes: the HTML is too long for the html "
"parameter. Set PREVIEW_URL to a page you can upload to.")
break
content = (slices(original, "Original page") + slices(rendered, "Your render")
+ [text_block(f"{page_text}\n<current_html>\n{html}\n</current_html>"
f"\n\n{FIX_PROMPT}")])
html = extract_html(ask(content))
save(html, f"fix pass {n}")
if __name__ == "__main__":
main(sys.argv[1])
Some notes on the choices in this script:
- The image comes from a signed link. With
response_type=jsonthe API returnsstoragePath, a signed URL valid for one hour, and the script downloads the JPEG from it. It is one request more than an inline image and keeps the API response small. - Images come before the instructions. Anthropic recommends putting images before the question, and labeling each slice with its position helps the model keep the order.
- The page text is capped at 30,000 characters so a very long page does not crowd out the output. Raise it if your pages need it.
- No JavaScript and no external files keeps the result easy to review and easy to render for the fix passes. Ask for Tailwind or React instead if that is your stack; the rest of the pipeline stays the same.
- Placeholders instead of images. A screenshot does not contain image URLs, so a model asked for
<img>tags makes up paths. Placeholders are honest, and you swap in real assets afterwards. index.htmlis saved after each step, so a failed fix pass never costs you the draft before it.
Already have a screenshot?
Pass a file path instead of a URL: python screenshot_to_code.py page.png. The script skips the capture, scales a retina screenshot back to 1280 px wide, and slices it the same way. Two things change:
- There is no page text, so the model reads the wording from the pixels. Check headings and prices in the result by hand.
- The fix passes still work, because they render the generated HTML, not the original page.
The same with GPT
Only three functions talk to the model. To use OpenAI, run pip install openai, set OPENAI_API_KEY and OPENAI_MODEL, and replace the "Model (Claude)" block of the script, including the client and MODEL lines at the top, with this:
from openai import OpenAI
client = OpenAI()
MODEL = os.environ["OPENAI_MODEL"] # any current vision-capable GPT model
def text_block(text):
return {"type": "input_text", "text": text}
def image_block(jpeg_bytes):
return {"type": "input_image", "detail": "high",
"image_url": "data:image/jpeg;base64,"
+ base64.b64encode(jpeg_bytes).decode()}
def ask(content):
response = client.responses.create(
model=MODEL, input=[{"role": "user", "content": content}],
)
return response.output_text
Set detail explicitly. The default is auto, and what auto, high and original mean differs by model: on GPT-5.5, original keeps up to 6,000 px and 10,000 patches, so it would accept a 1280 × 6000 page at full size. Slicing works the same on every model, which is why the script uses it.
Step 3: how the render-and-fix passes work
A first draft tends to get the structure and the text right and miss on spacing, column widths and section order. Models catch these errors much better when they see their own output next to the original. So the script renders the generated file at the same width, sends both sets of slices plus the current HTML, and asks for a corrected file.
SnapshotFlow renders HTML directly through the html parameter (base64 encoded), so you do not need to host the draft. Three details in render():
- Query-string size. The
htmlparameter travels in the URL, and servers cap the request line plus headers (Node.js, for example, at 16 KB by default). URL-safe base64 without padding avoids percent-encoding, and the 12,000-character check, about 9 KB of HTML, leaves room for the rest of the request. On our API, 15,000 characters of encoded HTML went through and 20,000 returned HTTP 431 (Request Header Fields Too Large). - Larger drafts need a preview URL. Set
PREVIEW_URLto any page you can upload to, such as a static host or a branch deploy. The script pauses, you uploadindex.html, and it captures that URL withcache=false; without it, the second capture of the same URL could come from the cache. WithoutPREVIEW_URL, the script keeps the first draft and skips the fix passes. - Same width, same settings. If the original is captured at 1280 px and the render at another width, the model will "fix" differences that come from the viewport, not from its code.
FIX_PASSES = 2 is a cap, not a promise. If the draft is still far off after two passes, look at the capture and the prompt before adding more passes.
When the draft is on a public preview URL, you can also get a number for "how close is it". GET /diff captures two URLs at the same viewport; with response_type=json it returns diff_percent instead of the diff image. Placeholder images and slightly different fonts keep it from reaching zero, so watch whether it drops between passes rather than aiming for a target value.
The agent version with MCP
If you are rebuilding a page inside an existing project, a coding agent can run the same loop and write the code straight into your components. Connect the SnapshotFlow MCP server (setup guides for Claude Code and Cursor). The agent gets a screenshot tool that accepts a URL or base64 HTML, and an extract_text tool for the wording. Then ask:
Use the snapshotflow screenshot tool to capture https://example.com/pricing
at width 1280 with cookie banners blocked, and extract_text for the copy.
Rebuild the page as app/pricing/page.tsx using our existing components
in components/ui. Then capture the local preview URL I give you, compare
it with the original and fix the differences. Stop after two rounds.
The agent cannot capture localhost through a hosted API, so give it a tunnel or preview deploy URL for the comparison step. The html input also works for a single file.
What screenshot to code gets wrong
| Problem | Why | What helps |
|---|---|---|
| Invented text | The screenshot was shrunk until text was unreadable | Slices of 900 px and extract_content=true |
| Broken or made-up image paths | Pixels do not contain URLs | Placeholders, then real assets from your own source |
| Wrong fonts | The model can only guess a typeface from its shape | Tell it the font family if you know it |
| Desktop-only layout | One screenshot shows one breakpoint | A second capture at 390 px with viewport_mobile=true |
| No behavior | Menus, tabs, carousels and forms are not visible in a still image | Describe the interactions in the prompt, or capture each state with click |
| A rebuilt cookie banner or chat bubble | It was in the screenshot | block_cookie_banners and hide_selectors |
The output is a good first draft of static markup. It is not your production frontend: it has no data, no state and no accessibility review. Plan on a developer pass, the same as with any generated code.
Whose site you copy
The safe uses are your own pages: migrating an old site to a new stack, recovering a page whose source is lost, turning a production page into a starting point for a redesign, or prototyping from an approved mockup.
Rebuilding someone else's site can copy their text, images, logos and design, which may be protected by copyright and trademark law, and their terms of service may forbid it. Use other sites for layout reference, write your own copy and use your own assets. Our guide to the legal side of website screenshots covers the capture itself; it is not legal advice.
FAQ
Which model is best for screenshot to code?
Current Claude, GPT and Gemini models all produce usable HTML from a clear screenshot. The quality of the input matters more than the model: a readable capture plus the page text beats a better model given one shrunken full-page image. Try two models on your own pages before you commit to one.
Can I convert a screenshot to HTML without an API key?
You can paste a screenshot into a chat app and ask for HTML. It works for a single section. For a whole page, the image limits above still apply, so paste it in slices.
How do I convert a URL to code instead of a screenshot?
Capture the URL first, then run the same pipeline. Sending the page's raw HTML instead does not work well on modern sites: single-page apps send almost empty HTML, and the real markup is buried in framework code. The screenshot shows what the user sees.
Can it generate React or Tailwind instead of plain HTML?
Yes. Change the rules in the prompt. For the render step, ask for a static HTML export as well, or render the component on a preview URL and capture that.
How much does one page cost?
One SnapshotFlow capture for the original, one per fix pass, plus model tokens. A 6,000 px page is about 10,000 image tokens per set of slices, and each fix pass sends two sets plus the current HTML, so count on tens of thousands of input tokens per finished page. Check your model's current price per token.
Sources and further reading
- Anthropic: Vision, image limits, resizing and token cost by model tier
- OpenAI: Images and vision, detail levels and patch-based resizing
- abi/screenshot-to-code on GitHub, the open-source app
- Sending screenshots to Claude and GPT on this site, for page analysis rather than code generation
- HTML to image API on this site, more on rendering HTML you generate
Try it: 300 free screenshots, no card
Capture the original, get the page text in the same call, and render each draft for comparison. The free plan covers 300 captures for the lifetime of the account.