Real-world Example Library
This chapter provides four business script templates that can be directly applied to real projects, covering the most common multi-account automation scenarios.
Example 1: Auto-fill Account and Login
Scenario: Automatically logging into various platforms (e-commerce backends, social media, ad accounts, etc.).
import requests
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
API_URL = "http://127.0.0.1:8186"
SESSION_ID = "replace_with_your_session_id"
DRIVER_PATH = r"C:\Program Files (x86)\Mbbrowser_v7.10.20.219\chromedriver.exe"
def get_driver_from_mbbrowser(session_id: str) -> webdriver.Chrome | None:
"""Utility function: Open Mbbrowser environment and return Selenium driver"""
resp = requests.post(
f"{API_URL}/api/v1/browser/start",
json={"Session_ID": session_id},
timeout=30
)
data = resp.json()
if data.get("code") != 0:
print(f"❌ Environment startup failed: {data.get('message')}")
return None
debugger_address = data["data"]["http"]
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", debugger_address)
service = Service(executable_path=DRIVER_PATH)
driver = webdriver.Chrome(service=service, options=chrome_options)
return driver
def auto_login():
driver = get_driver_from_mbbrowser(SESSION_ID)
if not driver:
return
wait = WebDriverWait(driver, 20)
try:
# ── 1. Open Login Page ──────────────────────────────────────
driver.get("https://example.com/login")
# ── 2. Wait for account field and input account ──────────────
username_input = wait.until(
EC.visibility_of_element_located((By.ID, "username"))
)
username_input.clear()
username_input.send_keys("my_account@email.com")
time.sleep(0.5) # Brief pause to simulate human rhythm
# ── 3. Input Password ───────────────────────────────────────
password_input = driver.find_element(By.ID, "password")
password_input.clear()
password_input.send_keys("my_password_123")
time.sleep(0.3)
# ── 4. Click Login Button ───────────────────────────────────
login_btn = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))
)
login_btn.click()
# ── 5. Wait for successful login sign (URL redirect to dashboard)
wait.until(EC.url_contains("/dashboard"))
print(f"✅ Login successful! Current Page: {driver.current_url}")
# ── 6. After successful login, Mbbrowser automatically saves Cookies
# Next time the environment is opened manually or via script, it will remain logged in.
print("🔒 Cookies automatically saved to Mbbrowser environment.")
except Exception as e:
print(f"❌ Exception during login: {e}")
driver.save_screenshot("login_error.png") # Screenshot on error
finally:
driver.quit()
if __name__ == "__main__":
auto_login()Example 2: Inject Cookies for Instant Login (Bypass Steps)
Scenario: You already have the Cookie data for an account and want to bypass the login page directly.
def inject_cookies_and_enter():
driver = get_driver_from_mbbrowser(SESSION_ID)
if not driver:
return
# ── 1. Must first open the target domain to set its Cookies ──────
driver.get("https://www.amazon.com")
# ── 2. Prepare your Cookie data ───────────────────────────────
cookies = [
{
"name": "session-id",
"value": "123-4567890-1234567",
"domain": ".amazon.com",
"path": "/",
"secure": True
},
{
"name": "ubid-main",
"value": "130-1234567-7654321",
"domain": ".amazon.com",
"path": "/"
}
]
# ── 3. Inject Cookies one by one ──────────────────────────────
driver.delete_all_cookies() # Clear old cookies (optional)
for cookie in cookies:
driver.add_cookie(cookie)
print(f"✅ Injected {len(cookies)} Cookies")
# ── 4. Refresh page to apply Cookies ─────────────────────────
driver.refresh()
time.sleep(2)
# ── 5. Verify successful login ───────────────────────────────
if "Hello" in driver.page_source or "Account" in driver.title:
print("✅ Cookie injection successful, logged in!")
else:
print("⚠️ Cookies might be expired; please reacquire.")
driver.quit()NOTE
Mbbrowser Secret: Mbbrowser automatically persists Cookies for each environment. Every time you log in, the Cookies are saved. Next time you open the environment, you'll still be logged in.
Example 3: Batch Data Scraping (Product List)
Scenario: Scraping protected page data while logged in, such as audience reports or competitor prices.
def scrape_product_list():
driver = get_driver_from_mbbrowser(SESSION_ID)
if not driver:
return
wait = WebDriverWait(driver, 20)
all_products = []
try:
# Open product list page
driver.get("https://example.com/products?page=1")
# ── Pagination Scraping Logic ───────────────────────────────
page_num = 1
while True:
print(f"📄 Scraping Page {page_num}...")
# Wait for list container to load
wait.until(EC.presence_of_element_located(
(By.CSS_SELECTOR, ".product-list")
))
# Scrape all products on this page
items = driver.find_elements(By.CSS_SELECTOR, ".product-item")
for item in items:
try:
name = item.find_element(By.CSS_SELECTOR, ".name").text.strip()
price = item.find_element(By.CSS_SELECTOR, ".price").text.strip()
all_products.append({"name": name, "price": price, "page": page_num})
except Exception:
pass # Skip individual failures
print(f" Scraped {len(items)} items on this page, total {len(all_products)}")
# Find "Next" button; stop if not found or disabled
next_btns = driver.find_elements(
By.CSS_SELECTOR, "a.pagination-next:not([aria-disabled='true'])"
)
if not next_btns:
print("✅ Final page reached, scraping complete!")
break
next_btns[0].click()
page_num += 1
time.sleep(1.5) # Brief wait after page turn
finally:
driver.quit()
# Output results (can write to CSV or Database)
print(f"\nScraped {len(all_products)} products total:")
for p in all_products[:5]:
print(f" {p['name']} - {p['price']}")
return all_productsExample 4: Multi-account Concurrency
Scenario: Operating multiple Mbbrowser environments simultaneously for true parallel efficiency.
import threading
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
API_URL = "http://127.0.0.1:8186"
DRIVER_PATH = r"C:\Program Files (x86)\Mbbrowser_v7.10.20.219\chromedriver.exe"
# List of Session_IDs for concurrency
SESSION_LIST = [
"ENV_ID_1",
"ENV_ID_2",
"ENV_ID_3",
"ENV_ID_4",
"ENV_ID_5",
]
def operate_one_account(session_id: str, thread_id: int):
"""Operation logic for a single account (executed per thread)"""
print(f"[Thread {thread_id}] Starting environment {session_id[:8]}...")
try:
# Start Mbbrowser environment
resp = requests.post(
f"{API_URL}/api/v1/browser/start",
json={"Session_ID": session_id},
timeout=30
)
data = resp.json()
if data.get("code") != 0:
print(f"[Thread {thread_id}] ❌ Failed: {data.get('message')}")
return
debugger_address = data["data"]["http"]
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", debugger_address)
service = Service(executable_path=DRIVER_PATH)
driver = webdriver.Chrome(service=service, options=chrome_options)
# ── Insert your account logic here ──
driver.get("https://example.com")
print(f"[Thread {thread_id}] ✅ Operation complete: {driver.title}")
driver.quit()
except Exception as e:
print(f"[Thread {thread_id}] ❌ Exception: {e}")
finally:
# Best to close environments to release resources regardless of success
requests.post(
f"{API_URL}/api/v1/browser/stop",
json={"Session_ID": session_id},
timeout=10
)
def batch_operate():
"""Execute all accounts concurrently"""
threads = []
for i, session_id in enumerate(SESSION_LIST):
t = threading.Thread(
target=operate_one_account,
args=(session_id, i + 1)
)
threads.append(t)
t.start()
# Wait for all threads to complete
for t in threads:
t.join()
print("\n🎉 All accounts processed!")
if __name__ == "__main__":
batch_operate()IMPORTANT
Concurrency Recommendations: Each environment consumes memory (approx. 300-600MB). Control concurrency based on your machine's specs:
- 16GB RAM → 10-15 environments simultaneously
- 32GB RAM → 20-30 environments simultaneously
Excess concurrency causes RAM shortage, slow browser response, or crashes.
Example 5: Complete Production-Grade Script Framework
A framework closer to real production environments, including error handling, retries, and logging:
import requests
import time
import logging
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.common.exceptions import TimeoutException, WebDriverException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# Logging Config
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S"
)
logger = logging.getLogger(__name__)
API_URL = "http://127.0.0.1:8186"
DRIVER_PATH = r"C:\Program Files (x86)\Mbbrowser_v7.10.20.219\chromedriver.exe"
class MBBrowserSession:
"""Mbbrowser Selenium Session Manager (Support retries & context management)"""
def __init__(self, session_id: str, retry: int = 3):
self.session_id = session_id
self.retry = retry
self.driver = None
def start(self) -> webdriver.Chrome:
"""Starts environment and returns driver (auto-retry on failure)"""
for attempt in range(1, self.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.get("code") == 0:
debugger_address = data["data"]["http"]
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", debugger_address)
service = Service(executable_path=DRIVER_PATH)
self.driver = webdriver.Chrome(service=service, options=chrome_options)
logger.info(f"[{self.session_id[:8]}] Started ✅")
return self.driver
else:
logger.warning(f"[{self.session_id[:8]}] Failed: {data.get('message')}")
except Exception as e:
logger.error(f"[{self.session_id[:8]}] Exception: {e}")
time.sleep(2 ** attempt) # Exponential Backoff
raise RuntimeError(f"Session {self.session_id} failed after {self.retry} attempts")
def stop(self):
"""Closes Mbbrowser environment"""
if self.driver:
try:
self.driver.quit()
except Exception:
pass
requests.post(
f"{API_URL}/api/v1/browser/stop",
json={"Session_ID": self.session_id},
timeout=10
)
logger.info(f"[{self.session_id[:8]}] Environment closed")
def __enter__(self):
return self.start()
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()
return False # Don't silence exceptions
# ── Usage Example ──────────────────────────────────────────────
SESSION_ID = "replace_with_your_session_id"
with MBBrowserSession(SESSION_ID) as driver:
wait = WebDriverWait(driver, 15)
try:
driver.get("https://www.mbbrowser.com")
logger.info(f"Page Title: {driver.title}")
driver.save_screenshot("result.png")
except TimeoutException:
logger.error("Page load timeout; check network or proxy.")
except WebDriverException as e:
logger.error(f"WebDriver error: {e}")Best Practice Summary
| Practical Advice | Description |
|---|---|
| ✅ Always Use Explicit Waits | Replace time.sleep() with WebDriverWait for stability. |
| ✅ Screenshot on Errors | Call driver.save_screenshot() in except blocks for debugging. |
✅ Use with for Management | Context managers ensure the browser is closed properly. |
| ✅ Control Pacing | Add time.sleep(0.3~1.0) between key actions to mimic human pace. |
| ✅ ID-Identified Logs | Print Session_ID in every log during concurrency for traceability. |
| ❌ No Hard Sleeps in Loops | Drastically reduces efficiency; use wait conditions instead. |
| ❌ Don't Share Drivers | Each thread/account needs its own Session_ID and driver instance. |
TIP
🎉 Congratulations! You've mastered the full automation stack for Mbbrowser + Selenium.
For issues, review the Core API Reference or check the Automation Script Manager for managing Python scripts in the client.
