Live Demo: Talk to AI, Generate Complete Scripts in One Step
This chapter provides a complete, real-world demonstration of the process from "saying a requirement in natural language" to "getting a script ready to run," with detailed descriptions for each step.
Demo Scenario
Business Context: You have 20 Amazon seller accounts and need to check the number of "Pending" orders under each account every day, summarizing them into an Excel report for your team.
Traditional Method: Manually log in to each account one by one, record order counts, and fill in Excel. This takes about 2 hours.
Using AI + Mbbrowser: Describe the requirements, AI generates the script, and the script handles the rest. The total time spent is 15 minutes (including configuration).
Step 1: Preparation (5 Minutes)
NOTE
Assuming you have completed the following configurations from previous chapters:
- ✅ Cursor or Antigravity is installed.
- ✅ Mbbrowser Rules Package is loaded into Cursor.
- ✅ Mbbrowser ApiServer is started (
http://127.0.0.1:8186). - ✅ Your Amazon accounts are already logged in within the Mbbrowser environments (Cookies are saved).
Prepare the sessions.txt File
In your project folder, create sessions.txt and fill in all the environment IDs you want to operate on:
a1b2c3d4e5f6789012345678901234ab
b2c3d4e5f67890123456789012345bcd
c3d4e5f678901234567890123456cde
... (one Session_ID per line, total 20 lines)Step 2: Input Requirements in Cursor (30 Seconds)
Press Ctrl + L to open Cursor Chat and enter the following:
I have an Mbbrowser sessions.txt file with 20 account Session_IDs, one per line.
These accounts are already logged into Amazon in the Mbbrowser environments.
Please help me generate a Python script with the following features:
1. Read all Session_IDs from sessions.txt.
2. Batch open all environments (up to 10 concurrently).
3. After each environment is taken over by Playwright:
a. Wait for the page to load (environments usually stay on the last closed page).
b. Navigate to https://www.amazon.com/gp/orders-v2/list (Amazon seller order page).
c. Wait for the .a-row.shipment element to appear (signaling order list load).
d. Count the number of .shipment-status-buyerPending elements on the page (these are "Pending" orders).
e. Write the first 8 characters of Session_ID + pending order count to the results.
4. Close all environments after all operations are complete.
5. Save results to amazon_orders_[today's date].xlsx,
Columns: Env ID (first 8 chars), Pending Order Count, Check Time, Status.
Save screenshots to an errors/ folder if exceptions occur and record "Check Failed" in the result table.Step 3: AI Generates Code (Approx. 30 Seconds)
After receiving the request, Cursor's AI will generate the full code. The generated result should look like this:
"""
Mbbrowser + Amazon Order Check Script
Automatically checks the count of pending orders across all environments.
"""
import threading
import datetime
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
import openpyxl
from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout
# ==============================
# Configuration (Modify as needed)
# ==============================
APISERVER = "http://127.0.0.1:8186"
SESSIONS_FILE = "sessions.txt"
MAX_WORKERS = 10 # Max concurrency
ERRORS_DIR = Path("errors")
ERRORS_DIR.mkdir(exist_ok=True)
results_lock = threading.Lock()
results = []
# ==============================
# APIServer Wrapper
# ==============================
def start_env(session_id: str) -> dict | None:
try:
resp = requests.post(
f"{APISERVER}/api/v1/browser/start",
json={"Session_ID": [session_id], "isHeadless": False},
timeout=30
)
data = resp.json()
if data["code"] == 0:
return data["data"]["listid"][0]
except Exception as e:
print(f"[{session_id[:8]}] APIServer Error: {e}")
return None
def stop_env(session_id: str):
try:
requests.post(
f"{APISERVER}/api/v1/browser/stop",
json={"Session_ID": session_id}, # Stop usually expects a string
timeout=10
)
except Exception:
pass
# ==============================
# Single Account Task
# ==============================
def check_orders(session_id: str):
now = datetime.datetime.now().strftime("%H:%M:%S")
env_short = session_id[:8]
env_data = start_env(session_id)
if not env_data:
with results_lock:
results.append({
"env_id": env_short,
"pending_orders": "N/A",
"check_time": now,
"status": "Failed to Open Environment"
})
return
port = env_data.get("browser_CDP_Port")
ws = f"ws://127.0.0.1:{port}/json/version"
pw = sync_playwright().start()
try:
browser = pw.chromium.connect_over_cdp(ws)
context = browser.contexts[0]
page = context.pages[0] if context.pages else context.new_page()
# Access Amazon Order Page
page.goto(
"https://www.amazon.com/gp/orders-v2/list",
wait_until="domcontentloaded",
timeout=20000
)
# Wait for order list to load
page.wait_for_selector(".a-row.shipment", timeout=15000)
# Count pending orders
pending = page.locator(".shipment-status-buyerPending").count()
print(f"[{env_short}] ✅ Pending Orders: {pending}")
with results_lock:
results.append({
"env_id": env_short,
"pending_orders": pending,
"check_time": now,
"status": "Success"
})
browser.close()
except PWTimeout:
page.screenshot(path=str(ERRORS_DIR / f"{env_short}_timeout.png"))
with results_lock:
results.append({
"env_id": env_short,
"pending_orders": "N/A",
"check_time": now,
"status": "Page Timeout"
})
except Exception as e:
try:
page.screenshot(path=str(ERRORS_DIR / f"{env_short}_error.png"))
except Exception:
pass
with results_lock:
results.append({
"env_id": env_short,
"pending_orders": "N/A",
"check_time": now,
"status": f"Exception: {str(e)[:50]}"
})
finally:
try:
pw.stop()
except Exception:
pass
stop_env(session_id)
# ==============================
# Main Program
# ==============================
def main():
# Read Session_ID list
session_ids = [
line.strip()
for line in Path(SESSIONS_FILE).read_text().splitlines()
if line.strip()
]
print(f"📋 Total {len(session_ids)} accounts, Max Concurrency {MAX_WORKERS}")
# Concurrent Execution
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
futures = {pool.submit(check_orders, sid): sid for sid in session_ids}
for future in as_completed(futures):
sid = futures[future]
try:
future.result()
except Exception as e:
print(f"[{sid[:8]}] Uncaught Exception: {e}")
# Save Excel Report
today = datetime.date.today().strftime("%Y%m%d")
filename = f"amazon_orders_{today}.xlsx"
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Order Check Results"
ws.append(["Env ID (first 8)", "Pending Orders", "Check Time", "Status"])
for r in results:
ws.append([r["env_id"], r["pending_orders"], r["check_time"], r["status"]])
wb.save(filename)
# Summary Report
success = sum(1 for r in results if r["status"] == "Success")
print(f"\n{'='*40}")
print(f"✅ Success: {success} / {len(results)}")
print(f"📄 Report saved to: {filename}")
print(f"❌ Error screenshots in: errors/ directory")
if __name__ == "__main__":
main()Step 4: Install Dependencies & Run (2 Minutes)
After generating the code, AI usually advises on the dependencies to install:
pip install playwright requests openpyxlThen run directly:
python check_amazon_orders.pyExpected Output
📋 Total 20 accounts, Max Concurrency 10
[a1b2c3d4] ✅ Pending Orders: 3
[b2c3d4e5] ✅ Pending Orders: 0
[c3d4e5f6] ✅ Pending Orders: 7
...
========================================
✅ Success: 18 / 20
📄 Report saved to: amazon_orders_20260226.xlsx
❌ Error screenshots in: errors/ directoryCommon Issues & AI Correction Tips
"Script running but can't find order elements"
Select the relevant code and press Ctrl + K. Input:
The selector for the Amazon page has changed. The actual order row selector is .order-info, and the pending status selector is .order-status-pending. Please update the code."Add a feature: collect order details as well"
Continue the conversation in Chat:
Based on the code above, after collecting the order count, please also collect the order ID (.a-fixed-right-grid-col .a-link-normal) and expected ship date (.expected-ship-date) for each pending order, and record them in the Excel."Concurrency too fast, causing crash; need rate limiting"
Based on the ThreadPoolExecutor, add a 3-second wait before starting each new task to avoid memory issues from opening too many environments simultaneously.Summary: Best Practices for AI Script Writing
[ Preparation ]
1. Rules Package injected → AI understands all Mbbrowser interfaces.
2. Confirm APIServer is started.
[ Requirement Description ]
The more specific, the better:
✅ "Visit https://xxx, wait for #main-content element, click .order-btn, wait for success popup."
❌ "Help me manage orders."
[ Generation ]
Usually, 80% is usable immediately. Fix minor issues via follow-up chat.
[ Iterative Optimization ]
"Add feature xx based on this" → AI appends changes without rewriting.IMPORTANT
Important Reminder: AI-generated code might occasionally have minor errors. Always run a test on 1-2 test accounts before broad deployment. Expand to all accounts only after verification.
TIP
🎉 Congratulations! You now master the full set of methods to generate automation scripts for Mbbrowser using AI models.
Encountered issues? Refer to the corresponding chapters:
- Interface mismatch? → Rules Package to confirm APIServer usage.
- No script idea? → Skills Package to find scenario-based templates.
