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.

What you can build in this article・An automated operation script that prevents misclicks by attaching "number badges" to actionable targets on screen and having the AI select them・A token-saving design that keeps API costs and latency down by avoiding the accumulation of past screenshots.

📊 Operational Verification Status: Autonomous execution test completed on physical environments (verified normal operation with 0 errors).

Language: Python 3.10 or higher.

Key Libraries: playwright>=1.42.0, pydantic>=2.6.0, openai>=1.14.0.

Target Model: GPT-4o (a similar design can also be applied to models supporting vision input, such as Claude 3.5 Sonnet).

Prerequisites: Basic Python syntax, fundamental knowledge of HTML elements and CSS selectors.

Why AI Browser Automation Fails in Production.

How the "Three Coordinate Drifts" Cause Missed Clicks.

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

Complete Copy-and-Paste Python Script.

Three Pitfalls When Deploying to Production and Workaround Techniques.

Summary: Checklist for Stable Autonomous Operation.

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.

Missed clicks due to differences in screen resolutionThe image coordinates returned by the AI conflict with the coordinate references handled internally by the browser, causing it to keep clicking a few pixels outside the button or in unrelated blank space.

Infinite retries on non-actionable "apparent buttons"The AI mistakenly identifies buttons that are mid-animation or hidden behind a loading transparent overlay as "clickable," leading to repeated timeout errors on the Playwright side and halting execution.

Surging Costs and Rate Limit Errors from Accumulating Image History Because high-resolution screenshots are continuously added to the conversation history with every action, token limits or API rate limits are hit within about 10 steps.

Industry observers note that 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.

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.

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.

According to recent reports, 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.

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.

Sources indicate that 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.

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.

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.

This design offers three major advantages:.

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.

It has been revealed that 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.

Sources indicate that 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.

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

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

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

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.

According to recent reports, symptom: The script attaches badges before a menu finishes opening, causing elements to move within the 0.2 seconds immediately following the capture. A discrepancy arises between the image the AI saw and the actual click target.

Workaround: Right before attaching the badges, insert a wait function that "waits until DOM changes on the screen come to a complete stop for 0.2 seconds" (also set a maximum 1-second timeout as a countermeasure against infinite animations).

Symptom: When scrolling down a page, badges are also rendered on buttons that have slipped behind the fixed top navigation bar, causing numbers to overlap and making them illegible to the AI.

Workaround: Add an elementFromPoint check to the JavaScript filter condition to determine whether the element is truly the topmost visible one at its center coordinates.

Symptom: While text recognition worked cleanly on a local Mac or Windows machine, switching to a headless Linux environment such as AWS causes text to appear jagged and pixelated, degrading the AI's recognition accuracy.

Workaround: Explicitly lock the text anti-aliasing settings and scaling factor using browser launch options (*When handling pages containing Japanese, it is also key to install Japanese fonts such as fonts-noto-cjk inside the container).

In AI agents that automate browser actions, only a fraction of complications 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.

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

💻 Ultra-Fast, 24/7 Autonomous Server (Japan's Fastest Cloud): XServer VPS Cloud - Ideal as a high-load-tolerant server environment for continuously monitoring and autonomously running AI agents and Python scripts.

🛠️ Recommended APIs & Tools: Claude API / OpenAI API / Ollama (Local LLM Execution Environment).

📌 Read also:

→ Read original article