Skip to content

Real-world Example Library

This chapter provides five complete script templates that can be directly applied to real projects, covering the most common multi-account automation scenarios. Each case includes both JavaScript and Python versions.


Example 1: Auto Login and Maintaining State

Scenario: Automatically logging into a target platform for a specific Mbbrowser environment.

javascript
// JavaScript Version
const { chromium } = require('playwright');
const axios = require('axios');

const API_URL    = 'http://127.0.0.1:8186';
const SESSION_ID = 'replace_with_your_session_id';

async function autoLogin() {
  // ── Open Mbbrowser Environment ─────────────────────────────
  const { data } = await axios.post(`${API_URL}/api/v1/browser/start`, {
    Session_ID: SESSION_ID
  });
  if (data.code !== 0) throw new Error(`Startup failed: ${data.message}`);
  const wsEndpoint = data.data.ws;

  const browser = await chromium.connectOverCDP(wsEndpoint);
  const context = browser.contexts()[0];
  const page    = context.pages()[0] || await context.newPage();

  try {
    // ── Open Login Page and Fill Form ──────────────────────────
    await page.goto('https://example.com/login', { waitUntil: 'domcontentloaded' });

    // getByRole is the recommended positioning method in Playwright
    await page.getByLabel('Email').fill('my_account@email.com');
    await page.getByLabel('Password').fill('my_password_123');
    await page.getByRole('button', { name: 'Log In' }).click();

    // Wait for redirect to dashboard (sign of successful login)
    await page.waitForURL('**/dashboard', { timeout: 15000 });
    console.log('✅ Login successful! Current URL:', page.url());

    // Mbbrowser automatically persists Cookies; no need to re-login next time.
    console.log('🔒 Cookies automatically saved to Mbbrowser environment');
  } catch (e) {
    console.error('❌ Login failed:', e.message);
    await page.screenshot({ path: 'login_error.png', fullPage: true });
  } finally {
    await browser.close();
  }
}

autoLogin().catch(console.error);
python
# Python Version
import requests
from playwright.sync_api import sync_playwright

API_URL    = "http://127.0.0.1:8186"
SESSION_ID = "replace_with_your_session_id"

def auto_login():
    resp = requests.post(
        f"{API_URL}/api/v1/browser/start",
        json={"Session_ID": SESSION_ID}, timeout=30
    )
    data = resp.json()
    if data["code"] != 0:
        print(f"❌ Startup failed: {data['message']}")
        return

    ws = data["data"]["ws"]
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp(ws)
        context = browser.contexts[0]
        page    = context.pages[0] if context.pages else context.new_page()

        try:
            page.goto("https://example.com/login", wait_until="domcontentloaded")
            page.get_by_label("Email").fill("my_account@email.com")
            page.get_by_label("Password").fill("my_password_123")
            page.get_by_role("button", name="Log In").click()
            page.wait_for_url("**/dashboard", timeout=15000)
            print(f"✅ Login successful! Current URL: {page.url}")
        except Exception as e:
            print(f"❌ Login failed: {e}")
            page.screenshot(path="login_error.png", full_page=True)
        finally:
            browser.close()

if __name__ == "__main__":
    auto_login()

Scenario: Injecting existing Cookie data to bypass login forms and gain immediate access.

javascript
// JavaScript Version
async function injectAndLogin(page, context) {
  // Note: Must open the target domain first to set Cookies for it
  await page.goto('https://shop.example.com', { waitUntil: 'commit' });

  // Inject prepared Cookie array
  await context.addCookies([
    { name: 'session_id', value: 'SID_abcdef123456', domain: '.example.com', path: '/' },
    { name: 'auth_token', value: 'Bearer_xyz789',   domain: '.example.com', path: '/' }
  ]);

  // Refresh page to apply Cookies
  await page.reload({ waitUntil: 'domcontentloaded' });

  // Verify successful entry
  const accountEl = page.getByRole('button', { name: 'My Account' });
  if (await accountEl.isVisible()) {
    console.log('✅ Cookie injection successful! Logged in.');
  } else {
    console.warn('⚠️ Cookies might be expired; please reacquire.');
  }
}

NOTE

Mbbrowser Secret: Once successfully logged in within an Mbbrowser environment, the Cookies are permanently saved in that environment's data directory. This "persistent environment" is the core value of a fingerprint browser!


Example 3: Scrapping API Data via Network Interception

Scenario: Scraping data directly from XHR/Fetch responses, which is more stable than parsing HTML.

javascript
// JavaScript Version
async function interceptAndCollect(page) {
  const collectedData = [];

  // ── Listen for target API responses ───────────────────────────
  page.on('response', async response => {
    if (response.url().includes('/api/products') && response.status() === 200) {
      try {
        const json = await response.json();
        if (json.data?.list) {
          collectedData.push(...json.data.list);
          console.log(`📦 Collected ${collectedData.length} product entries`);
        }
      } catch (e) {}
    }
  });

  // ── Open product page to trigger API requests ────────────────
  await page.goto('https://example.com/products');

  // ── Pagination Logic ─────────────────────────────────────────
  for (let i = 0; i < 5; i++) {
    const nextBtn = page.getByRole('button', { name: 'Next' });
    if (!await nextBtn.isVisible()) break;
    // Click Next and wait for data response
    await Promise.all([
      page.waitForResponse(r => r.url().includes('/api/products')),
      nextBtn.click()
    ]);
  }

  console.log(`✅ Collected ${collectedData.length} entries total`);
  return collectedData;
}

Example 4: Multi-account Concurrency

Scenario: Controlling multiple Mbbrowser environments simultaneously for parallel efficiency.

python
# Python Version —— Concurrency via Threading
import threading
import requests
from playwright.sync_api import sync_playwright

API_URL      = "http://127.0.0.1:8186"
SESSION_LIST = ["ENV_ID_1", "ENV_ID_2", "ENV_ID_3", "ENV_ID_4", "ENV_ID_5"]

def operate_one_account(session_id, thread_id):
    print(f"[Thread {thread_id}] Starting {session_id[:8]}...")
    try:
        resp = requests.post(f"{API_URL}/api/v1/browser/start", json={"Session_ID": session_id}, timeout=30)
        data = resp.json()
        if data["code"] != 0:
            print(f"[Thread {thread_id}] ❌ Failed: {data['message']}")
            return

        ws = data["data"]["ws"]
        with sync_playwright() as p:
            browser = p.chromium.connect_over_cdp(ws)
            context = browser.contexts[0]
            page    = context.pages[0] if context.pages else context.new_page()

            # ── Business Logic ──
            page.goto("https://example.com")
            print(f"[Thread {thread_id}] ✅ Complete: {page.title()}")
            browser.close()
    except Exception as e:
        print(f"[Thread {thread_id}] ❌ Exception: {e}")
    finally:
        requests.post(f"{API_URL}/api/v1/browser/stop", json={"Session_ID": session_id}, timeout=10)

if __name__ == "__main__":
    threads = [threading.Thread(target=operate_one_account, args=(sid, i+1)) for i, sid in enumerate(SESSION_LIST)]
    for t in threads: t.start()
    for t in threads: t.join()
    print("\n🎉 All accounts processed!")

IMPORTANT

Concurrency Recommendations:

  • 16GB RAM → 10-15 environments simultaneously
  • 32GB RAM → 20-30 environments simultaneously

Example 5: Production-Grade Framework (Retries & Logging)

python
# Python Production Framework
import threading
import requests
import logging
import time
from playwright.sync_api import sync_playwright, TimeoutError as PWTimeoutError

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(threadName)s] %(levelname)s %(message)s")
logger = logging.getLogger(__name__)

API_URL = "http://127.0.0.1:8186"

class MBPlaywrightSession:
    def __init__(self, session_id: str, max_retry: int = 3):
        self.session_id = session_id
        self.max_retry  = max_retry
        self._pw        = None
        self._browser   = None

    def start(self):
        for attempt in range(1, self.max_retry + 1):
            try:
                logger.info(f"[{self.session_id[:8]}] Attempting start (Try {attempt})")
                resp = requests.post(f"{API_URL}/api/v1/browser/start", json={"Session_ID": self.session_id}, timeout=30)
                data = resp.json()
                if data["code"] == 0:
                    self._pw      = sync_playwright().start()
                    self._browser = self._pw.chromium.connect_over_cdp(data["data"]["ws"])
                    logger.info(f"[{self.session_id[:8]}] ✅ Ready")
                    return self
            except Exception as e:
                logger.error(f"[{self.session_id[:8]}] Error: {e}")
            time.sleep(2 ** attempt)
        raise RuntimeError(f"Failed to start {self.session_id}")

    @property
    def page(self):
        context = self._browser.contexts[0]
        return context.pages[0] if context.pages else context.new_page()

    def stop(self):
        try:
            if self._browser: self._browser.close()
            if self._pw: self._pw.stop()
        except Exception: pass
        requests.post(f"{API_URL}/api/v1/browser/stop", json={"Session_ID": self.session_id}, timeout=10)

    def __enter__(self): return self.start()
    def __exit__(self, *args): self.stop()

# ── Usage ──
with MBPlaywrightSession("replace_with_your_session_id") as session:
    try:
        session.page.goto("https://www.mbbrowser.com")
        logger.info(f"Title: {session.page.title()}")
    except Exception as e:
        logger.error(f"Execution Error: {e}")

Comparison Summary

DimensionPuppeteerSeleniumPlaywright
Mbbrowser Fielddata.wsdata.httpdata.ws
Auto-waitManualManualBuilt-in
Network InterceptBasicNoPowerful
RecommendationJS DevsLegacy CodeNew Projects

TIP

🎉 You've mastered Mbbrowser + Playwright!

Visit playwright.dev for official docs, or refer to Automation Script Manager to manage your scripts in-client.