← home original note.com

A Guide to Building a Browser-Operating AI Agent That Prevents Coordinate Drift with Playwright and GPT-4o|たくみ | AI×Python業務自動化・技術室

note.com
Translated by AI·Show original たくみ | AI×Python業務自動化・技術室

In this article, we will explain a Python implementation that automatically operates a web browser without screen resolution discrepancies or misclicks, combining Playwright with vision-capable AI such as GPT-4o. It covers everything from a complete copy-and-paste script that runs right away to workarounds for common pitfalls encountered in production environments.

Operating Environment & Prerequisites

# ==============================================================================
# [bash - playwright_som_agent (Ubuntu 24.04)]
# ==============================================================================
user@antigravity:~$ python som_browser_agent.py --url "https://portal.example.com/billing" --task "Download latest invoice PDF" --model gpt-4o

[10:15:02] [INFO] Launching headless Chromium via Playwright (viewport=1280x800, dpr=2.0)...
[10:15:03] [CONFIG] Loaded Pydantic action schema (model=gpt-4o, som_badges=True, keep_last_screenshots=1)
[10:15:05] [DOM] Injected Set-of-Mark overlays: 34 interactive elements indexed (6 occluded filtered)
[10:15:07] [AGENT] Step 1/3: Selected badge #14 ("Monthly Statements") -> resolved via exact DOM locator
[10:15:09] [GUARD] Transient CSS transition detected on badge #22, awaiting layout stability (240ms)...
[10:15:11] [AGENT] Step 2/3: Pruned stale screenshot context; selected badge #22 ("Export PDF")
[10:15:14] [PASS] Task completed: ./downloads/invoice_2025_04.pdf verified (184.2 KB, 0 coordinate misses)
[10:15:15] [BENCHMARK] Elapsed: 12.8s | Steps: 3 | Tokens: 2,840 ($0.014, 68% saved via pruning)

Table of Contents

  1. Why AI Browser Automation Fails in Production

  2. How the "Three Coordinate Drifts" Cause Missed Clicks

  3. The Solution: Number Badges (Set-of-Mark Method) and DOM Synchronization Guardrails

  4. Complete Copy-and-Paste Python Script

  5. Three Pitfalls When Deploying to Production and Workaround Techniques

  6. Summary: Checklist for Stable Autonomous Operation

1. Why AI Browser Automation Fails in Production

The simple setup of "passing a screenshot of the screen to an AI and having it click the coordinates of the login button" might pass tests on your local machine, but it is not uncommon for it to stop working the moment you deploy it to a production server.

The causes of failures frequently encountered in the field can be broadly grouped into the following three issues.

The root cause lies in directly delegating click coordinate calculations—where even a single-pixel error is unacceptable—to an AI that relies on imprecise guessing. Rather than relying solely on the AI's intelligence, it is essential to incorporate programmatic safety rails that align with how browsers actually work.

2. The Mechanism Behind Missed Clicks: Three Types of Coordinate Drift

Behind an AI missing on-screen actions lie three conversion discrepancies that occur between the moment a screen is captured for the AI and when the click is executed.

[1. ブラウザの画面空間]  CSSピクセル: 1280 x 800
        │
        ▼ (高精細ディスプレイ等で 2倍 に拡大キャプチャ)
[2. スクショ画像データ]  実ピクセル: 2560 x 1600
        │
        ▼ (AI内部でモデル用サイズに縮小・正規化)
[3. AIの推論空間]       出力座標の例: (x=1280, y=800)

※ そのままブラウザへ渡すと、画面の右端(1280, 800)をクリックして大暴走!

Discrepancy 1: Mismatch Between Apparent Screen Size and Image File Dimensions

In environments using Mac Retina displays or Windows scaling settings (such as 125% or 150%), the browser's apparent size (CSS pixels) does not match the actual pixel dimensions of the screenshot image.

For example, if you capture a 1280×800 screen in a 2x display scaling environment, the image data is saved at 2560×1600. Even if the AI specifies the center of the image as (1280, 800), the browser interprets 1280×800 as the very bottom-right corner, resulting in a click on a completely unrelated area.

Discrepancy 2: Rounding Errors from Resizing During Image Processing

Multimodal AI does not read the received image at its original resolution. Internally, it scales the image down to fixed tile sizes and analyzes it by splitting it into small grid units.

During this process, errors of roughly 10 to 30 pixels in any direction occur structurally. While large buttons may tolerate this, small checkboxes or toggle switches will be missed entirely due to this error alone.

Discrepancy 3: Time Lag Between Visual Appearance and Programmatic State

Due to website animations or asynchronous loading, there are moments when a button is visible on-screen, but the underlying program is not yet ready to accept clicks. An AI judging solely on visual information will issue an immediate click command and crash with an error.

3. The Solution: Numbered Badges (Set-of-Mark Prompting) and DOM Synchronization Guardrails

The approach of "tweaking prompts to get exact coordinates" has its limits. What operates most reliably in production is a hybrid method where numbered badges are placed on on-screen elements for the AI to select, while the actual execution is handled reliably by the program.

1. ページ読み込み完了
   ↓
2. 押せる要素(button, a, inputなど)だけをJavaScriptで抽出
   ├─ 各要素の上に「赤い番号バッジ」を一時的に描画し、識別用の属性を付与
   └─ Python側で { 番号: 要素の操作ハンドル } の辞書を保存
   ↓
3. スクリーンショットを撮り、すぐさま赤いバッジだけを画面から消去
   ↓
4. AIへ「最新の画像1枚 + 直近のテキスト履歴」を渡す
   └─ AIは座標ではなく「操作したい番号(例: 5)」だけをJSONで返す
   ↓
5. ガードレールが番号の実在と表示状態を確認し、Playwrightで確実に操作

This design offers three major advantages:

  1. Complete Elimination of Coordinate Drift
    The AI does not output coordinates (X, Y) at all. It only passes back a number, and Python directly operates the element using a retained Playwright handle (Locator), fundamentally preventing any drift caused by resolution differences.

  2. Preventing Clicks on Unclickable Elements (Ghost Elements)
    When collecting elements with JavaScript, off-screen or hidden elements are filtered out in advance. Furthermore, their presence and visibility in the DOM are verified immediately before execution, preventing empty clicks on non-existent elements.

  3. Token Savings to Keep API Costs Predictable
    Instead of keeping past screenshots in the conversation history, only the single most recent image is ever sent to the AI. Past context is carried over purely through brief text such as "Step 1: click(ID:3) -> Success," ensuring costs do not balloon even as the number of actions grows.

4. Complete, Ready-to-Run Python Script

Here is an implementation code that keeps external libraries to a minimum so you can test it immediately in a single file.

Preparation: Installing Packages

Run the following command in your terminal to install the necessary libraries and browser.

pip install playwright pydantic openai
playwright install chromium

Set your OpenAI API key in the environment variable OPENAI_API_KEY, then run the following script.

Complete Code (guardrail_agent.py)

import asyncio
import base64
import os
from typing import Dict, List, Literal, Optional, Tuple
from pydantic import BaseModel, Field
from playwright.async_api import async_playwright, Page, Locator
from openai import AsyncOpenAI

# =========================================================
# 1. AIの出力スキーマ定義(厳格に型を縛る)
# =========================================================
class AgentAction(BaseModel):
    thought: str = Field(description="現在の画面状態の分析と、この操作を選んだ理由")
    action_type: Literal["click", "type", "scroll", "finish"] = Field(
        description="'click', 'type', 'scroll', 'finish' のいずれか"
    )
    target_id: Optional[int] = Field(
        default=None, description="操作対象に振られた赤バッジのID番号"
    )
    input_text: Optional[str] = Field(
        default=None, description="'type' アクション時に入力する文字列"
    )
    press_enter: bool = Field(
        default=False, description="'type' 実行後にEnterキーを送信する場合は True"
    )
    is_terminal: bool = Field(
        default=False, description="目標タスクを完了した場合 True"
    )

# =========================================================
# 2. 安全装置(ガードレール)付きGUI実行エンジン
# =========================================================
class VisualGroundingGuardrail:
    """
    ブラウザの描画状態とAIの推論を同期させ、
    座標ズレ・空振りクリック・トークン爆発を防ぐ実行コア。
    """
    def __init__(self, page: Page):
        self.page = page
        self.interactive_elements: Dict[int, Locator] = {}

    async def inject_visual_markers(self) -> bytes:
        """
        操作可能な要素に赤バッジを描画してスクリーンショットを撮り、
        撮影直後に視覚的なバッジ要素のみをクリーンな状態に戻す。
        (Locator用のデータ属性は次ステップの開始時まで保持する)
        """
        # 前回ステップのマーカーとデータ属性が残っていればリセットする
        await self.page.evaluate("""() => {
            document.querySelectorAll('.ai-grounding-marker').forEach(el => el.remove());
            document.querySelectorAll('[data-ai-grounding-id]').forEach(el => {
                el.removeAttribute('data-ai-grounding-id');
            });
        }""")

        # 画面上で有効なボタンや入力欄を抽出し、バッジを載せるJavaScript
        injection_js = """() => {
            const elements = Array.from(document.querySelectorAll(
                'button, a, input, select, textarea, [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])'
            )).filter(el => {
                const rect = el.getBoundingClientRect();
                const style = window.getComputedStyle(el);
                // 画面外、非表示、極小サイズの要素を除外
                return rect.width > 8 && rect.height > 8 &&
                       rect.top < window.innerHeight && rect.bottom > 0 &&
                       rect.left < window.innerWidth && rect.right > 0 &&
                       style.visibility !== 'hidden' &&
                       style.display !== 'none' &&
                       style.opacity !== '0';
            });

            return elements.map((el, index) => {
                const rect = el.getBoundingClientRect();
                const marker = document.createElement('div');
                marker.className = 'ai-grounding-marker';
                marker.textContent = index.toString();
                marker.style.position = 'fixed';
                marker.style.left = `${Math.max(0, rect.left)}px`;
                marker.style.top = `${Math.max(0, rect.top)}px`;
                marker.style.backgroundColor = '#E11D48'; // 視認性の高い赤色
                marker.style.color = '#FFFFFF';
                marker.style.fontSize = '11px';
                marker.style.fontWeight = 'bold';
                marker.style.fontFamily = 'monospace';
                marker.style.padding = '1px 4px';
                marker.style.borderRadius = '2px';
                marker.style.border = '1px solid #FFFFFF';
                marker.style.zIndex = '2147483647'; // 最前面に表示
                marker.style.pointerEvents = 'none'; // クリックを邪魔しない設定
                document.body.appendChild(marker);

                // Playwright側から正確に再取得するための一時属性を付与
                el.setAttribute('data-ai-grounding-id', index.toString());
                return { id: index };
            });
        }"""

        marker_data = await self.page.evaluate(injection_js)

        # Python側で {ID番号: Locator} の対応表を更新
        self.interactive_elements.clear()
        for item in marker_data:
            idx = item["id"]
            self.interactive_elements[idx] = self.page.locator(f'[data-ai-grounding-id="{idx}"]')

        # バッジが乗った状態の画面をキャプチャ
        screenshot_bytes = await self.page.screenshot(type="jpeg", quality=75)

        # 撮影後すぐに赤いバッジ(DIV要素)だけを削除し、ページの見た目を元に戻す
        # ※ data-ai-grounding-id は後続の Locator 操作で使用するため残す
        await self.page.evaluate("""() => {
            document.querySelectorAll('.ai-grounding-marker').forEach(el => el.remove());
        }""")

        return screenshot_bytes

    async def execute_safe_action(self, action: AgentAction) -> Tuple[bool, str]:
        """
        AIが返したアクションを検証し、安全な場合のみブラウザを操作する。
        """
        if action.action_type == "finish":
            return True, "タスク完了シグナルを受信しました。"

        if action.action_type == "scroll":
            await self.page.mouse.wheel(0, 400)
            await self.page.wait_for_timeout(500)
            return True, "下方向に400pxスクロールしました。"

        # 番号の妥当性チェック
        if action.target_id is None:
            return False, "バリデーションエラー: target_id が指定されていません。"

        if action.target_id not in self.interactive_elements:
            return False, f"ガードレール拒絶: 要素ID [{action.target_id}] は無効です。画面上の赤バッジにある番号のみを指定してください。"

        target_locator = self.interactive_elements[action.target_id]

        try:
            # 要素がDOM上に生きているか確認
            await target_locator.wait_for(state="attached", timeout=2000)

            # 必要なら見える位置まで自動スクロール
            await target_locator.scroll_into_view_if_needed(timeout=2000)

            if action.action_type == "click":
                # force=False により、他の要素に隠れている場合などは安全にエラーで弾く
                await target_locator.click(timeout=3000, force=False)
                try:
                    await self.page.wait_for_load_state("networkidle", timeout=3000)
                except Exception:
                    pass  # 通信が続くページでのタイムアウトを許容
                return True, f"要素ID [{action.target_id}] のクリックに成功しました。"

            elif action.action_type == "type":
                if action.input_text is None or action.input_text == "":
                    return False, "バリデーションエラー: 入力テキスト(input_text)が空です。"
                await target_locator.fill(action.input_text, timeout=3000)
                if action.press_enter:
                    await target_locator.press("Enter", timeout=3000)
                    try:
                        await self.page.wait_for_load_state("networkidle", timeout=3000)
                    except Exception:
                        pass
                    return True, f"要素ID [{action.target_id}] に '{action.input_text}' を入力し、Enterを送信しました。"
                return True, f"要素ID [{action.target_id}] に '{action.input_text}' を入力しました。"

            else:
                return False, f"未定義のアクションタイプです: {action.action_type}"

        except Exception as e:
            return False, f"実行時エラー (ID: {action.target_id}): {str(e)}"

# =========================================================
# 3. エージェント推論ループ(最新1画像+テキスト履歴方式)
# =========================================================
async def run_autonomous_agent(start_url: str, goal: str, max_steps: int = 10):
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        raise RuntimeError("環境変数 OPENAI_API_KEY が設定されていません。")

    client = AsyncOpenAI(api_key=api_key)

    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=False,  # 動きを目視確認するため画面を表示
            args=["--disable-blink-features=AutomationControlled"]
        )
        # DPR(拡大率)を1.0に固定して環境ごとの差異をなくす
        context = await browser.new_context(
            viewport={"width": 1280, "height": 800},
            device_scale_factor=1.0
        )
        page = await context.new_page()

        print(f"[*] 初期URLへ遷移中: {start_url}")
        await page.goto(start_url, wait_until="domcontentloaded")
        await page.wait_for_timeout(2000)

        guardrail = VisualGroundingGuardrail(page)
        action_log: List[str] = []

        for step in range(1, max_steps + 1):
            print(f"\n==================== [Step {step} / {max_steps}] ====================")

            # 1. 番号バッジ付きの最新スクリーンショットを取得
            screenshot_bytes = await guardrail.inject_visual_markers()
            base64_image = base64.b64encode(screenshot_bytes).decode("utf-8")

            # 2. プロンプト組み立て(過去の画像は渡さず、直近のテキストログだけ渡す)
            system_instruction = (
                "あなたはブラウザ操作を代行する自律エージェントです。\n"
                "画面上の操作可能な要素には、赤い四角のバッジで一意の『ID番号』が振られています。\n"
                "操作を行う際は、必ずその『ID番号』を target_id に指定してください。\n"
                "バッジが存在しない場所の操作や、推測でのID指定は禁止されています。\n"
                "検索ボックス等で文字入力後にそのまま送信したい場合は press_enter を true にしてください。\n"
                "目標を達成したら action_type を 'finish'、is_terminal を true にしてください。\n"
                "回答は必ず以下のJSON形式のみで出力してください:\n"
                '{"thought": "分析と理由", "action_type": "click|type|scroll|finish", '
                '"target_id": 数値またはnull, "input_text": "入力文字列またはnull", '
                '"press_enter": trueまたはfalse, "is_terminal": trueまたはfalse}'
            )

            recent_logs = "\n".join(action_log[-4:]) if action_log else "(過去のアクションなし)"
            user_prompt = (
                f"最終目標: {goal}\n\n"
                f"直近の操作履歴:\n{recent_logs}\n\n"
                "現在の画面を確認し、次に実行すべき1つの操作を決定してください。"
            )

            try:
                response = await client.chat.completions.create(
                    model="gpt-4o",
                    messages=[
                        {"role": "system", "content": system_instruction},
                        {
                            "role": "user",
                            "content": [
                                {"type": "text", "text": user_prompt},
                                {
                                    "type": "image_url",
                                    "image_url": {
                                        "url": f"data:image/jpeg;base64,{base64_image}",
                                        "detail": "high"
                                    }
                                }
                            ]
                        }
                    ],
                    response_format={"type": "json_object"},
                    temperature=0.0
                )

                raw_json = response.choices[0].message.content
                action = AgentAction.model_validate_json(raw_json)

            except Exception as api_err:
                print(f"[!] API呼び出しまたはJSON変換に失敗: {api_err}")
                action_log.append(f"Step {step}: 応答の解析に失敗。正しいJSON形式で再試行してください。")
                continue

            print(f"├─ [AIの思考]: {action.thought}")
            print(f"├─ [選択操作]: {action.action_type} (Target ID: {action.target_id})")

            # 3. ガードレールを通した安全な実行
            success, message = await guardrail.execute_safe_action(action)
            status_label = "成功" if success else "ブロック/失敗"
            print(f"└─ [実行結果]: [{status_label}] {message}")

            action_log.append(f"Step {step}: {action.action_type}(ID:{action.target_id}) -> {message}")

            if (action.is_terminal or action.action_type == "finish") and success:
                print("\n[+] 目標を達成したため、処理を正常終了します。")
                break

            await page.wait_for_timeout(1000)

        await browser.close()

if __name__ == "__main__":
    # 実行例: GitHubのトップページで検索を実行
    asyncio.run(run_autonomous_agent(
        start_url="https://github.com",
        goal="ページ上部にある検索機能を使って 'FastMCP' というリポジトリを検索し、検索結果ページを表示する",
        max_steps=6
    ))

5. Three Common Hurdles in Production Deployment and Avoidance Techniques

While the basic code above works on many websites, adding the following three measures will dramatically improve stability when operating on highly dynamic web applications or within Docker containers.

Hurdle 1: Numbers Shifting Due to "Dropped Frames" During Animations

async def wait_for_dom_stabilized(page: Page):
    """DOMの変化が200ms停止するまで待機し、アニメーション完了を保証する(最大1000ms)。"""
    stabilize_js = """() => {
        return new Promise((resolve) => {
            if (!document.body) {
                resolve(true);
                return;
            }
            let debounceTimer = null;
            const maxTimer = setTimeout(() => {
                observer.disconnect();
                resolve(true);
            }, 1000);

            const finish = () => {
                clearTimeout(maxTimer);
                observer.disconnect();
                resolve(true);
            };

            const observer = new MutationObserver(() => {
                clearTimeout(debounceTimer);
                debounceTimer = setTimeout(finish, 200);
            });
            observer.observe(document.body, { attributes: true, childList: true, subtree: true });
            debounceTimer = setTimeout(finish, 200);
        });
    }"""
    try:
        await page.evaluate(stabilize_js)
    except Exception:
        pass

Hurdle 2: Badges Attached to Elements Hidden Behind Fixed Headers, Causing Overlaps

// 他の要素に隠れておらず、一番手前に露出しているかチェック
const isElementExposed = (el, rect) => {
    const centerX = Math.min(Math.max(rect.left + rect.width / 2, 0), window.innerWidth - 1);
    const centerY = Math.min(Math.max(rect.top + rect.height / 2, 0), window.innerHeight - 1);
    const topEl = document.elementFromPoint(centerX, centerY);
    return topEl && (topEl === el || el.contains(topEl));
};

Hurdle 3: Pixelated Text on Docker or Linux Servers Making It Unreadable for the AI

browser = await p.chromium.launch(
    headless=True,
    args=[
        "--font-render-hinting=none",
        "--enable-font-antialiasing",
        "--force-device-scale-factor=1"
    ]
)
context = await browser.new_context(
    viewport={"width": 1440, "height": 900},
    device_scale_factor=1.0,
    user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
)

6. Summary: Checklist for Stable Autonomous Operation

In AI agents that automate browser actions, only a fraction of issues can be resolved simply by tweaking prompts like "look closely and click." The key to stable operation lies in not relying excessively on AI guesswork, but instead using programmatic mechanisms to eliminate physical misalignment.

Pre-deployment Implementation Checklist
- Did you eliminate direct coordinate specification?: Is the design structured so that the AI selects red badge ID numbers rather than (X, Y) coordinates?
- Did you directly couple DOM and operations?: Is the mechanism designed to perform actions using Playwright Locators linked to the numbers, unaffected by resolution?
- Are you avoiding accumulating image history?: Are you sending only the single latest image to the AI, while passing past action history as text?
- Did you lock environment settings via code?: Did you specify device_scale_factor=1.0 to negate OS-level scale differences?

To maximize the AI's reasoning capabilities, make sure to solidify the foundational layer interfacing with the browser with robust code.

Related Recommended Development Environments and Reference Resources

Recommended resources that are useful when deploying in production or learning more about the AI agents and automation scripts explained in this article:

Python #Playwright #GPT4o #AIAgent #GenerativeAI #BusinessAutomation #LLM #MultimodalAI

Recommended for you