Web-browsing agents in Python with Browser Use and Playwright
What actually happens when you combine Playwright with Browser Use 1.0 and Gemini 3.5 Flash Lite? This hands-on Python tutorial builds a reproducible bookstore test app with a v1-to-v2 DOM redesign, connects Playwright to Browser Use over CDP, and shares real speed, token, and failure benchmarks.

Table of Contents5 sections
My pure Playwright script logged into a local bookstore app, filtered two pages of results, checked three product pages, and returned clean JSON in 0.91 s. When I flipped the app to a redesigned DOM layout, the same script died after 5.58 s waiting for a #category-select element that no longer existed. I expected a web-browsing agent built with Browser Use and Gemini 3.5 Flash Lite to absorb that layout change and pass three runs out of three.
That is not what happened. Across nine live benchmark runs on my Ubuntu 24.04.5 LTS laptop (Intel Core i3-1315U, 15.2 GiB RAM, Python 3.12.3), browser-use==1.0.8 paired with gemini-3.5-flash-lite solved the redesigned layout with exact accuracy, but only once in the three-run hybrid benchmark, plus one earlier smoke run. The other eight runs failed to transient HTTP 503 demand spikes, step exhaustion, or timeouts. Along the way, I also ran into four practical surprises that rarely show up in quickstart guides: browser-use 1.0 no longer wraps Playwright, Playwright's new_context() hides login cookies from CDP tabs, @tools.action tools cannot be called inside the agent's Python REPL, and the built-in LLM judge reported 'success': True on a run that failed ground-truth checks.
How Browser Use 1.0 and Playwright actually fit together
Most older tutorials still import BrowserSession or browser_use.llm.google and describe Browser Use as a thin LLM wrapper around Playwright. In browser-use==1.0.8, that architecture is gone. When I tried importing browser_use.llm.google during testing, the package raised a clear migration error:
ModuleNotFoundError: browser_use.llm.google was removed in browser-use 1.0.
Open an issue at https://github.com/browser-use/browser-use/issues if you need it.
In 1.0: from browser_use import ChatGoogle.
Migration guide: https://github.com/browser-use/browser-use/blob/main/MIGRATING.md
According to the project's MIGRATING.md, version 1.0 replaces the old one-action-per-step DOM loop with a persistent Python REPL backed by browser-harness==0.1.13 helpers and raw Chrome DevTools Protocol (CDP), orchestrated on pydantic-ai-slim==2.66.0. Instead of returning a single click payload per turn, the model writes short Python cells that drive Chrome over CDP.
Playwright (playwright==1.65.2) still has a clear job next to Browser Use 1.0. Playwright gives you fast, deterministic control over browser launch, login forms, and post-run assertions at zero token cost. Browser Use gives you an adaptive agent that reads unfamiliar pages and recovers when CSS selectors change. Because both tools speak CDP, you can launch Chromium with Playwright, sign in deterministically, and hand the live browser to Browser Use through Browser(cdp_url=..., keep_alive=True).
To test both tools side by side, I kept the experiment in its own Python 3.12 virtual environment managed by uv 0.11.16. Isolation mattered right away: browser-use 1.0.8 on PyPI pins google-genai==2.34.0, which clashed with google-genai 3.5.0 in my parent workspace. Pinning exact versions in pyproject.toml avoids surprise API breaks while keeping dependencies reproducible:
[project]
name = "devbooks-browser-agent"
version = "0.1.0"
requires-python = ">=3.11,<3.14"
dependencies = [
"browser-use==1.0.8",
"playwright==1.65.2",
"pydantic>=2.14.0",
"python-dotenv>=1.2.4",
]
Installing dependencies with uv sync --python 3.12 resolved 71 packages and installed 68 packages in 53.62 s. Running uv run playwright install chromium downloaded Chrome for Testing 159.0.8154.6 (199.3 MiB) plus Chrome Headless Shell (125.7 MiB) and FFmpeg (2.2 MiB) in 218.37 s. With GOOGLE_API_KEY in .env and ANONYMIZED_TELEMETRY=false, I verified the installed stack (browser-use==1.0.8, browser-harness==0.1.13, playwright==1.65.2, pydantic-ai-slim==2.66.0, google-genai==2.34.0, pydantic==2.14.3).
To avoid CAPTCHAs and moving third-party sites, I built a local stdlib http.server web app called DevBooks Catalog (demo_site/server.py). It serves 10 technical books behind a cookie-protected /login page ([email protected] / reader-2026), paginates /catalog at 3 items per page, and puts ISBN and stock status only on /book/<id> detail pages. Every runner receives the same goal: find all Python books priced strictly under $45.00 with a rating of 4.5 or higher, inspect each matching detail page for its ISBN and in_stock boolean, and sum their prices into a CatalogReport Pydantic model (src/devbooks_agent/models.py). Three books match (Fluent Async Python at $39.00, Fast Python CLI Tools at $29.50 and out of stock, plus High-Throughput Python APIs at $44.00 on page 2), totaling $112.50.
The server supports two layouts via --layout v1|v2. Layout v1 uses plain semantic controls (#category-select, #max-price, article.book-card, a.next-page). Layout v2 simulates a frontend redesign: filters move inside a collapsed id="toggle-drawer" panel with renamed inputs (topic, price_cap), cards become div.tile-wrap, pagination changes to More titles →, and detail pages switch from a list to a <dl class="spec-grid">.
Baseline: fast Playwright on v1 and instant breakage on v2
The baseline scraper (src/devbooks_agent/playwright_scraper.py) logs in, selects Python, filters by price 45, walks pagination, opens each candidate detail page, and returns CatalogReport:
await login_with_playwright(page, base_url)
await page.select_option("#category-select", "Python")
await page.fill("#max-price", "45")
await page.click("#apply-filters")
await page.wait_for_selector("article.book-card")
With a 5000 ms timeout and three fresh runs per layout, playwright_v1 passed 3/3 with exact matches in a median of 0.91 s (range 0.85–0.94 s) at zero token cost. A scrubbed clean re-run from a fresh git clone confirmed that speed, returning a median of 0.98 s (range 0.92–1.02 s, +7.7% drift).
Pointing the exact same script at v2 failed 3/3 in a median of 5.58 s (range 5.55–5.60 s; clean re-run median 5.57 s, -0.2% drift) waiting on #category-select:
TimeoutError: Page.select_option: Timeout 5000ms exceeded.
Playwright logged in cleanly because /login did not change, then timed out on the missing #category-select locator. That single failure is the whole reason to reach for an LLM browser agent.
Debugging gemini-3.5-flash-lite inside Browser Use 1.0
Getting a clean standalone run with gemini-3.5-flash-lite (src/devbooks_agent/browser_use_agent.py) took three real debugging detours that changed how I configured Agent.
First, ChatGoogle("gemini-3.5-flash-lite") works out of the box, but my first two live runs hit upstream 503 UNAVAILABLE high-demand errors from Google AI Studio. Inspecting browser_use.agent.loop.build_agent showed why: browser-use injects settings['max_retries'] = 2 for Google models unless 'max_retries' is already present in the model's settings dictionary. Passing GoogleModel from pydantic_ai.models.google with explicit HttpRetryOptions and "max_retries": 4 preserved retries without discarding the REPL session.
Second, a direct A/B probe of gemini-3.5-flash-lite showed that thinking_low passed 4/4 calls in 1.22–6.31 s with zero errors, while thinking_medium (the default browser-use requests for Google models) failed 2/4 calls with 503 UNAVAILABLE and spiked to 34.43 s. Setting "thinking_level": "LOW" inside build_llm() cut request stalls right away:
retry_options = types.HttpRetryOptions(
attempts=5,
initial_delay=1.5,
max_delay=8.0,
exp_base=2.0,
http_status_codes=[429, 500, 502, 503, 504],
)
return GoogleModel(
model,
provider=GoogleProvider(api_key=api_key, retry_options=retry_options),
settings={
"max_retries": 4,
"google_thinking_config": {"thinking_level": "LOW"},
},
)
Third, in default REPL mode, gemini-3.5-flash-lite spent eight steps writing fragile JavaScript snippets, hitting SyntaxError: Unexpected token ':' and ModuleNotFoundError: No module named 'bs4'. Switching to mode="ultrafast" gave the model accessibility-tree helpers (bu.click, bu.type), matching a comment inside browser_use.agent.service noting that lighter models perform much better in ultrafast mode. I also registered a custom @tools.action helper called verify_total_cost. During my first successful run, the model wasted steps 12 through 14 hitting NameError: name 'verify_total_cost' is not defined because it tried calling the tool inside its Python REPL cell instead of issuing a direct tool call. Adding one sentence to the prompt cleared up that confusion.
The hybrid pattern: Playwright for login, Browser Use over CDP
In src/devbooks_agent/hybrid_cdp_agent.py, Playwright launches Chromium with --remote-debugging-port, signs in on /login, hands the CDP URL to Browser Use, and captures a verification screenshot when the agent finishes. Credentials never enter the LLM prompt, and the agent skips login turns completely.
My first attempt hit a subtle session bug. I launched Chromium with pw.chromium.launch(headless=True) and called chromium.new_context(), which creates an isolated incognito BrowserContext in Playwright. When Browser Use connected over CDP and opened a tab, Chrome created that tab in its default context with no session cookie. A short diagnostic script proved the difference directly:
persistent=False (new_context) -> CDP new tab landed on: ['http://127.0.0.1:33897/login']
persistent=True -> CDP new tab landed on: ['http://127.0.0.1:41913/catalog']
Switching to launch_persistent_context with a temporary profile directory fixed session handoff immediately:
context = await pw.chromium.launch_persistent_context(
user_data_dir=profile_dir,
headless=True,
viewport={"width": 1280, "height": 900},
args=[f"--remote-debugging-port={cdp_port}"],
)
page = context.pages[0] if context.pages else await context.new_page()
await login_with_playwright(page, base_url)
agent = Agent(
task=make_catalog_only_task(base_url),
llm=build_llm(model),
browser=Browser(cdp_url=cdp_url, keep_alive=True),
tools=build_tools(),
output_model_schema=CatalogReport,
mode="ultrafast",
reasoning="low",
workspace=workspace,
judge=judge,
)
result = await agent.run(max_steps=max_steps, timeout=180)
I added this CDP cookie-sharing check to tests/test_project.py. All five offline tests pass in 6.79 s locally (9.22 s on the clean re-run).
Benchmark numbers and where things broke
With the code frozen at commit aa9f229, I ran three fresh trials per configuration (judge=False during timed runs) against the same local app:
| Configuration | Exact Match | Median (s) | Range (s) | Median Steps | Median Tokens (in / out) | Median Cost |
|---|---|---|---|---|---|---|
playwright_v1 |
3/3 | 0.91 | 0.85–0.94 | 0 | 0 / 0 | $0.0000 |
playwright_v2 |
0/3 | 5.58 | 5.55–5.60 | 0 | 0 / 0 | $0.0000 |
browser_use_v1 |
0/3 | 54.15 | 53.24–64.58 | 3 | 9,013 / 185 | $0.0032 |
browser_use_v2 |
0/3 | 165.31 | 81.39–174.31 | 10 | 44,661 / 1,731 | $0.0150 |
hybrid_cdp_v2 |
1/3 | 114.18 | 78.43–166.41 | 5 | 16,139 / 632 | $0.0064 |
The data split my original hypothesis in two. On v1, Playwright was 86.2x faster than the successful hybrid_cdp_v2 run (0.91 s vs 78.43 s) and free. On v2, hybrid_cdp_v2 Run 1 proved the agent really can adapt without selector updates: in 13 steps (78.43 s, 89,064 input tokens, 2,983 output tokens, $0.0217), it inspected div.tile-wrap, corrected its own ISBN regex on step 9, matched all three books and $112.50 exactly, and let Playwright save a 39,475-byte screenshot of /book/8. An earlier smoke test also matched 100% on v2 in 15 steps (172.45 s).
Across the nine formal LLM trials, however, only 1/9 matched ground truth. Five of nine runs aborted with ModelUnavailableError: status_code: 503 even with LOW thinking and four retries. The other three missed because of step or timeout limits. Two failure modes stood out as warnings for production work:
- Forced-delivery fabrication: On
browser_use_v2Trial 1, spending steps on login and re-filtering exhaustedmax_steps=20before the agent openedFast Python CLI Tools. On the forced final turn,gemini-3.5-flash-liteinvented ISBN978-1-0981-8123-7(real:978-1-4842-8811-5) and reported"in_stock": true(real:false), while still claiming it verified every detail page. - False-positive LLM judge: In a separate
judge=Truedemo run onv2(207.20 s, 4 steps), the agent failed ground-truth validation ("exact_match": false), yetbrowser-use's built-in judge returned'success': True.
For sites you control or scrape on a schedule, write pure Playwright first: 0.91 s at $0 beats a 78.43 s agent loop every time. Bring in Browser Use 1.0 when UIs shift faster than you want to maintain selectors, and pair it with Playwright via launch_persistent_context and Browser(cdp_url=..., keep_alive=True) so deterministic code owns authentication, assertions, and screenshots. If you choose gemini-3.5-flash-lite for that agent layer today on this workload, budget for HTTP 503 retries, mode="ultrafast", "thinking_level": "LOW", and deterministic post-run validation rather than trusting status="completed" or judge=True. My next test would benchmark the same hybrid CDP script against a heavier model like gemini-3.5-flash to see whether fewer REPL mistakes cut total runtime enough to beat the lite tier's lower per-token price.
The complete project, local DevBooks Catalog server, tests, and reproduce.sh script are available on GitHub:

