Production-grade guide to agent browser automation covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Agent Browser Automation describes the pattern where an AI agent controls a web browser programatically to navigate, interact with DOM elements, and extract state as part of a larger workflow. It matters when an agent must operate on UI‑only services, integrate with legacy web applications, or validate front‑end behavior without API equivalents. Unlike API‑driven agent work, browser automation requires managing a live rendering context, synchronising with asynchronous page loads, and handling the full stack of web transport (HTTP, TLS, script execution). This reference page covers the concrete steps to start a session, drive interaction, read results, and the failure modes that appear only in production.
The standardised way to talk to a browser from an agent is the WebDriver W3C protocol. The most common way to get a running endpoint locally is via a Docker image that bundles a browser and its corresponding driver binary.
docker run -d -p 4444:4444 selenium/standalone-chrome:latest
Once the container is running, a new session is created with a POST to the /session endpoint. The request body is a capabilities object; the protocol recognises browserName to select the binary, and additional flags can be supplied under goog:chromeOptions or moz:firefoxOptions depending on the vendor implementation.
curl -X POST http://localhost:4444/wd/hub/session \
-H 'Content-Type: application/json' \
-d '{"capabilities": {"alwaysMatch": {"browserName": "chrome"}}}'
A successful response returns a JSON object containing sessionId and status: 0. If the requested browser binary is not available on the host, the response is:
500 {"value":{"error":"session not created","message":"chrome version must match ChromeDriver ...","stacktrace":"..."}}
Sessions are isolated: each sessionId owns its own browser process, cookies, local storage, and active URL. Cleaning up a session when the agent is done is essential to avoid port and process leaks.
curl -X DELETE http://localhost:4444/wd/hub/session/{sessionId}
Agents often need to reach intranet sites that require client‑side TLS certificates or an authenticated forward proxy. These are passed through the capabilities object rather than as command‑line flags, because the driver forwards them to the browser process at session start.
curl -X POST http://localhost:4444/wd/hub/session \
-H 'Content-Type: application/json' \
-d '{"capabilities": {"alwaysMatch": {"browserName": "chrome", "goog:chromeOptions": {"args": ["--disable-extensions"]}}}}'
To inject a client cert and key that the browser will present to the server:
curl -X POST http://localhost:4444/wd/hub/session \
-H 'Content-Type: application/json' \
-d '{"capabilities": {"alwaysMatch": {"browserName": "chrome", "goog:chromeOptions": {"args": ["--disable-extensions"], "chromeBinary": "/usr/bin/google-chrome"}}}}'
In practice the goog:chromeOptions map accepts args, extensions, and mobileEmulation. TLS client cert/key placement follows the same pattern used by the ChromeDriver binary: the agent mounts the PEM files into the container and references them via args: ["--client-cert-path=/certs/client.pem", "--client-key-path=/certs/client.key"]. If the cert is missing or untrusted, the browser emits:
net::ERR_CLIENT_AUTH_FAILURE
and the page load fails with a TimeoutException after the default wait period.
Proxy authentication is handled by adding proxy arguments to the same args list:
"args": ["--proxy-server=http://user:[email protected]:3128"]
If the proxy requires BypassList or PAC scripting, those flags are also accepted by the downstream browser binary, but they are not WebDriver‑protocol concepts; they are forwarded as‑is.
Once a session exists, navigation is a simple POST to the /url endpoint.
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/url \
-H 'Content-Type: application/json' \
-d '{"url": "https://example.com"}'
A 200 OK response confirms the browser has begun loading. If the URL scheme is unsupported or the host is unreachable, the protocol returns:
500 {"value":{"error":"invalid argument","message":"cannot load URL https://example.com","stacktrace":"..."}}
The WebDriver protocol defines a per‑session timeout configuration via /session/{sessionId}/timeouts. Setting an implicit wait tells the server to retry finding elements for the specified duration before throwing NoSuchElementError.
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/timeouts \
-H 'Content-Type: application/json' \
-d '{"implicit": 5000}'
Explicit waits are not a protocol endpoint; they are expressed by the agent inserting a JavaScript sleep or a polling loop via the /execute/sync endpoint. A typical pattern:
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/execute/sync \
-H 'Content-Type: application/json' \
-d '{"script": "return new Promise(r => setTimeout(() => r(document.readyState), 10000))"}'
The response contains the evaluated value ("complete" when the page has finished loading). If the agent polls this and the state never reaches "complete" within the agent’s own timeout, the agent should abort or retry, because the WebDriver server will not terminate the request on its own.
The protocol offers a strategy capability at session creation: "normal" (wait for onload), "eager" (return after DOMContentLoaded), or "none" (return immediately). Choosing "eager" can shave seconds off navigation time for SPA‑style apps where onload never fires, but it leaves the agent responsible for ensuring the UI is quiescent before interacting with elements.
Elements are located by sending a POST to /element with a locator strategy and value. The most common strategies are css selector and xpath.
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/element \
-H 'Content-Type: application/json' \
-d '{"using": "css selector", "value": "#submit-button"}'
The response is:
{"value": {"ELEMENT": "6066-11e4-a52e-4f735466cecf"}}
The ELEMENT identifier is a UUID‑like string that must be used in subsequent requests for that element. If the selector does not match any node, the response is:
500 {"value":{"error":"no such element","message":"Element not found","stacktrace":"..."}}
To populate a text input, first obtain the element ID as above, then POST to /element/{elId}/value. The payload is the literal text to type.
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/element/{elId}/value \
-H 'Content-Type: application/json' \
-d '{"text": "username123"}'
The server sends keystroke events to the browser, typing the string character by character. If the element is read‑only or disabled, the response is:
500 {"value":{"error":"element not interactable","message":"Cannot set value on disabled element","stacktrace":"..."}}
A click is sent to /element/{elId}/click. The browser scrolls the element into view (if necessary) and fires a mouseup at its centre point.
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/element/{elId}/click
If the element is obscured by another layer, overlay‑intercepted, or otherwise not pointer‑able, the error is:
500 {"value":{"error":"element not interactable","message":"element is not clickable at point","stacktrace":"..."}}
A common agent pattern is to first scroll the element into view via JavaScript execution, then retry the click.
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/execute/sync \
-H 'Content-Type: application/json' \
-d '{"script": "arguments[0].scrollIntoView({block: \"center\"});", "args": [{ "ELEMENT": "{elId}" }]}'
File inputs (<input type="file">) accept a POST to /element/{elId}/value with a payload that includes a file path. The protocol forwards the path to the browser, which resolves it relative to the browser’s current working directory (typically the container’s root or the user’s home). An absolute path is safest.
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/element/{elId}/value \
-H 'Content-Type: application/json' \
-d '{"value": ["/absolute/path/to/upload.txt"]}'
The value field for file inputs uses a special format: an array of one or more path strings, because a file input can accept multiple files.
A full‑page PNG (or PNG‑base64) is captured via POST /screenshot. The response body is a JSON object with a value field containing the base64‑encoded image data.
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/screenshot \
-H 'Content-Type: application/json' \
-d '{}'
If the session has already been closed, the response is:
500 {"value":{"error":"session not created","message":"session not created","stacktrace":"..."}}
The raw HTML of the current page is retrieved with POST /source.
curl -X POST http://localhost:4444/wd/hub/session/{sessionId}/source
The response body is a string containing the full <html>…</html> markup as rendered by the browser. This is useful for downstream parsing or for feeding an LLM to determine the next agent action.
Agents typically cycle through: decide → navigate → interact → observe → decide. A minimal loop can be expressed in bash using curl and jq for JSON parsing. Below is a concrete template that an agent script could source; it is not production‑ready but demonstrates the wire‑level primitives.
#!/usr/bin/env bash
set -euo pipefail
# 1. Start a session
SESSION_RESP=$(curl -s -X POST http://localhost:4444/wd/hub/session \
-H 'Content-Type: application/json' \
-d '{"capabilities": {"alwaysMatch": {"browserName": "chrome"}}}')
SESSION_ID=$(echo "$SESSION_RESP" | jq -r .value.sessionId)
# 2. Loop: navigate, screenshot, decide
for i in {1..10}; do
# Navigate
curl -s -X POST "http://localhost:4444/wd/hub/session/$SESSION_ID/url" \
-H 'Content-Type: application/json' -d '{"url": "https://example.com"}'
# Screenshot
SCREEN=$(curl -s -X POST "http://localhost:4444/wd/hub/session/$SESSION_ID/screenshot" \
-H 'Content-Type: application/json' -d '{}')
BASE64=$(echo "$SCREEN" | jq -r .value)
# (Here an LLM or policy would inspect $BASE64 and decide next action)
echo "Iteration $i: saved screenshot (truncated)…"
# Break condition example: if source contains a known token
SOURCE=$(curl -s -X POST "http://localhost:4444/wd/hub/session/$SESSION_ID/source")
if echo "$SOURCE" | grep -q "SUCCESS_TOKEN"; then
echo "Token found, terminating."
break
fi
done
# 3. Clean up
curl -s -X DELETE "http://localhost:4444/wd/hub/session/$SESSION_ID" > /dev/null
The loop demonstrates three concrete curl invocations (session creation, URL navigation, screenshot, source retrieval) and shows how the agent extracts values with jq. In a real deployment the loop would be driven by an LLM’s tool‑use output, but the underlying transport remains the same.
The most common silent failure is a version drift between the browser binary and the driver binary bundled in the Selenium image. When the Chrome browser is upgraded but the ChromeDriver remains at the old version, every POST /session request returns:
500 {"value":{"error":"session not created","message":"chrome version must be ...","stacktrace":"..."}}
The fix is to pull a newer selenium/standalone-chrome tag or to pin both binaries to the same upstream version.
In headless mode, browsers may encounter self‑signed certificates or expired intermediates. The WebDriver protocol does not expose a toggle to “ignore TLS errors”; the agent must supply the appropriate --ignore-certificate-errors flag through the capabilities args list. Omitting this flag causes the browser to abort navigation with net::ERR_CERT_AUTHORITY_INVALID, and the agent receives a generic TimeoutException after the implicit wait expires.
If an agent process crashes or is killed without issuing DELETE /session/{sessionId}, the underlying browser process continues running on the Docker host. The port 4444 remains occupied, and subsequent curl attempts return 500 session not created. Operators should implement a watchdog that periodically issues DELETE against any stale session IDs, or run each agent in its own container with a short‑lived selenium/standalone-chrome image.
The /execute/sync endpoint runs JavaScript in the browser’s main world. By default the script context is restricted to the page’s origin. Cross‑origin eval or fetch calls from within the executed script may be blocked by the page’s Content Security Policy or CORS headers. The agent should expect a SyntaxError or a network error if the script attempts to reach a different origin without proper permissions.
When sending a file path to a file input via /element/{elId}/value, the path is resolved by the browser process, not by the agent’s host filesystem. If the agent runs inside a container and mounts a volume at /data/uploads, the args must contain the path as seen from inside that container. Relative paths are resolved against the browser’s current working directory, which may differ from the agent’s working directory, leading to File not found errors that are easy to misdiagnose.
The core WebDriver protocol does not provide a mechanism to intercept outgoing HTTP requests or modify responses. Agents that need to stub APIs or mock latency must either use a browser extension (outside the scope of the standard protocol) or switch to a BiDi‑based implementation (e.g., Playwright’s CDP integration). Sticking to the W3C wire protocol means the agent can only observe the final rendered page, not the underlying traffic.
Frameworks that implement the WebDriver / BiDi pattern in this space include Playwright, Selenium and Puppeteer.
This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy