← Blog

Claude API Browser Automation Agent: Build Guide

2026-11-14 · 5 min read · SubToAPI Team

Building a browser automation agent with the Claude API

A Claude-powered browser automation agent is a program where Claude decides what action to take next on a webpage — click, type, scroll, extract text — while a headless browser like Playwright or Puppeteer actually executes that action. Claude doesn't touch the browser directly; it reasons over the current page state and returns a structured tool call, your code runs that call, and the result (new page state, screenshot, extracted text) goes back to Claude for the next decision.

This pattern is just Claude's tool use feature applied to browser control instead of database queries or weather APIs. If you've built a tool-calling assistant before, the mental model is identical: define tools with JSON schemas, run a loop, feed results back until the model decides it's done. The only new piece is the executor — a Playwright or Puppeteer instance that turns click_element or navigate_to into real DOM actions.

Why not just let Claude "browse" directly?

Claude has no native internet access from the API — it only responds to what you send it. Browser automation agents work by giving Claude a constrained set of actions it can request, and a feedback loop that reports what happened. This keeps the agent predictable: Claude can't do anything you haven't explicitly exposed as a tool, which matters a lot once the agent is filling out forms or clicking buttons on real sites.

Core architecture

A minimal agent has four pieces:

  1. A browser session (Playwright/Puppeteer) that persists across turns
  2. A set of tool definitions describing actions Claude can request
  3. An agent loop that sends page state to Claude, executes returned tool calls, and repeats
  4. A stop condition — either Claude signals completion or you hit a turn limit

Defining the tools

Keep the action set small and composable. Five tools cover most use cases:

[
  {
    "name": "navigate",
    "description": "Navigate the browser to a URL",
    "input_schema": {
      "type": "object",
      "properties": { "url": { "type": "string" } },
      "required": ["url"]
    }
  },
  {
    "name": "click",
    "description": "Click an element matching a CSS selector",
    "input_schema": {
      "type": "object",
      "properties": { "selector": { "type": "string" } },
      "required": ["selector"]
    }
  },
  {
    "name": "type_text",
    "description": "Type text into an input matching a CSS selector",
    "input_schema": {
      "type": "object",
      "properties": {
        "selector": { "type": "string" },
        "text": { "type": "string" }
      },
      "required": ["selector", "text"]
    }
  },
  {
    "name": "extract_text",
    "description": "Return the visible text content of the page",
    "input_schema": { "type": "object", "properties": {} }
  },
  {
    "name": "finish",
    "description": "Call when the task is complete, with a summary",
    "input_schema": {
      "type": "object",
      "properties": { "summary": { "type": "string" } },
      "required": ["summary"]
    }
  }
]

The agent loop

Here's a trimmed Node.js example using Playwright. The structure — send messages, check stop_reason, execute tool calls, push tool_result blocks back — matches Claude's standard tool use flow described in /docs/tools.

import { chromium } from "playwright";

const browser = await chromium.launch();
const page = await browser.newPage();

async function executeTool(name, input) {
  switch (name) {
    case "navigate":
      await page.goto(input.url);
      return "Navigated.";
    case "click":
      await page.click(input.selector);
      return "Clicked.";
    case "type_text":
      await page.fill(input.selector, input.text);
      return "Typed.";
    case "extract_text":
      return await page.innerText("body");
    case "finish":
      return input.summary;
  }
}

let messages = [
  { role: "user", content: "Go to example.com and extract the main heading." }
];

for (let turn = 0; turn < 10; turn++) {
  const res = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "x-api-key": process.env.ANTHROPIC_API_KEY,
      "anthropic-version": "2023-06-01",
      "content-type": "application/json"
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      tools: toolDefinitions,
      messages
    })
  });

  const data = await res.json();
  messages.push({ role: "assistant", content: data.content });

  const toolUse = data.content.find(b => b.type === "tool_use");
  if (!toolUse) break;
  if (toolUse.name === "finish") {
    console.log("Done:", toolUse.input.summary);
    break;
  }

  const result = await executeTool(toolUse.name, toolUse.input);
  messages.push({
    role: "user",
    content: [{ type: "tool_result", tool_use_id: toolUse.id, content: result }]
  });
}

await browser.close();

This is intentionally minimal — no vision, no retries, no rate limiting. It's enough to see the loop working end to end before adding complexity.

Adding vision for layout-sensitive sites

Text extraction breaks down on pages with dynamic layouts, canvas elements, or heavy JS rendering. Taking a screenshot and sending it as an image block lets Claude reason about visual position instead of raw DOM text:

const screenshot = await page.screenshot({ encoding: "base64" });
messages.push({
  role: "user",
  content: [
    { type: "image", source: { type: "base64", media_type: "image/png", data: screenshot } },
    { type: "text", text: "Here's the current page. What's next?" }
  ]
});

This roughly doubles token usage per turn, so cap screenshot frequency — only send one after navigation or form submission, not on every single action.

Guardrails that matter in production

Running this at scale

Once the agent works locally, the bottleneck shifts to API key management, concurrency limits, and knowing how much each automation run actually costs. If you're running this across a team or in production, SubToAPI turns your existing Claude access into a standard HTTPS API with per-application keys (sub_live_...), streaming support, and usage metadata per request — so you can see exactly how many tokens each agent run burned without building that tracking yourself. The tool-calling flow above works unchanged against SubToAPI's /v1/messages endpoint; see /docs/tools and /docs/streaming for the exact request shapes, or /docs/quickstart to get a key. Plans start at €9/month with a free trial — check /pricing for seat-based options if multiple people on your team are building agents against the same account.

FAQ

Does Claude control the browser directly? No. Claude only returns structured tool calls describing the action it wants (click, navigate, type). Your code executes the action with Playwright or Puppeteer and reports the result back to Claude.

Do I need vision/image input for browser agents? Not always. Text extraction works fine for simple, well-structured pages. Vision helps on JS-heavy or visually complex pages where DOM text doesn't reflect what's actually on screen.

What's the biggest failure mode to guard against? Infinite or near-infinite loops where the agent repeats the same failed action. Cap turns, log every tool call, and add selector/domain allowlists before pointing the agent at real third-party sites.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →