Run a headless browser
Run headless Chromium with Playwright, read a JavaScript page and save a screenshot.
| Template | Your own: 2 vCPU, 2 GiB, $0.048 per hour |
|---|---|
| Run time | About 9 seconds per page, after a one-time build of about 2 minutes |
| Cost of a run | Less than $0.001. 1,000 pages at 10 seconds each cost $0.13. |
| Cleanup | The finally block kills the sandbox. Delete the template with fdtn template delete my-browser --yes. |
1Build a browser template
Chromium is too large to install in each run. Save this Dockerfile in an empty folder:
Dockerfile
FROM python:3.12-slim-bookworm
# Put the browser in a shared folder, so the sandbox user finds it.
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
RUN pip install --no-cache-dir playwright==1.48.0 \
&& playwright install --with-deps chromium
WORKDIR /home/userBuild it with 2 GiB of memory. A browser needs more than 512 MiB.
$ fdtn template create my-browser --memory-mb 2048
...
Template my-browser is ready.Commands do not get the Dockerfile ENV lines. Pass them with envs at create, as the code below does.
2The code
scrape.py runs in the sandbox. It reads three quotes from a JavaScript page and saves a screenshot.
scrape.py
# Runs inside the sandbox: open a page that needs JavaScript, read it, save a screenshot. import json from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page() page.goto("https://quotes.toscrape.com/js/", wait_until="networkidle") quotes = [ {"text": q.locator(".text").inner_text(), "author": q.locator(".author").inner_text()} for q in page.locator(".quote").all()[:3] ] page.screenshot(path="/home/user/page.png", full_page=True) browser.close() print(json.dumps(quotes, indent=1, ensure_ascii=False))
This script runs on your computer. It starts the sandbox, runs scrape.py and downloads the screenshot.
browser.py
from fdtn import Sandbox sbx = Sandbox.create( "my-browser", # the template from step 1 timeout=600, envs={"PLAYWRIGHT_BROWSERS_PATH": "/ms-playwright"}, # Dockerfile ENV lines do not reach commands request_timeout=180, # the first start of a new template can take a minute metadata={"example": "browser"}, ) try: sbx.files.write("/home/user/scrape.py", open("scrape.py").read()) print(sbx.commands.run("python /home/user/scrape.py", timeout=120).stdout) png = sbx.files.read("/home/user/page.png", format="bytes") with open("page.png", "wb") as f: f.write(png) print(f"page.png: {len(png)} bytes") finally: sbx.kill()
import { readFile, writeFile } from 'node:fs/promises' import { Sandbox } from '@fdtn/sdk' const sbx = await Sandbox.create('my-browser', { // the template from step 1 timeoutMs: 600_000, envs: { PLAYWRIGHT_BROWSERS_PATH: '/ms-playwright' }, // Dockerfile ENV lines do not reach commands requestTimeoutMs: 180_000, // the first start of a new template can take a minute metadata: { example: 'browser' }, }) try { await sbx.files.write('/home/user/scrape.py', await readFile('scrape.py', 'utf8')) console.log((await sbx.commands.run('python /home/user/scrape.py', { timeoutMs: 120_000 })).stdout) const png = await sbx.files.read('/home/user/page.png', { format: 'bytes' }) await writeFile('page.png', png) console.log(`page.png: ${png.length} bytes`) } finally { await sbx.kill() }
3Run it
page.png (1280 pixels wide) is now in your folder.
$ python browser.py # or: node browser.mjs [ { "text": "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”", "author": "Albert Einstein" }, { "text": "“It is our choices, Harry, that show what we truly are, far more than our abilities.”", "author": "J.K. Rowling" }, { "text": "“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”", "author": "Albert Einstein" } ] page.png: 170204 bytes
Notes
wait_until="networkidle"waits until the JavaScript content is there.- Follow the terms of each site that you open.