How to Use
How to use our Lexmount Browser core functionality
Quick Start
This guide will help you get started with our Lexmount Browser core functionality. We provide SDKs in both Python and Node.js, and you can choose the appropriate version based on your needs.
Python SDK Usage Guide
Quick Access to Examples
You can also directly access our Python SDK Quickstart Repository on GitHub for ready-to-use examples.
Prerequisites
Please ensure you have Python 3.7 or higher installed.
1. Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate # Linux/macOS
# Or on Windows
# venv\Scripts\activate2. Install dependencies
pip install -r requirements.txt3. Configure environment variables
cp .env.example .env
# Edit the .env file and fill in your actual API Key and Project IDImportant Note
Please ensure your API Key is properly secured and not shared with others.
4. Run examples
We provide two example scripts to help you quickly understand how to use our service:
python demo.py # Basic demo
python light-demo.py # Light browser demoExample Code Explanation
Basic Demo (demo.py)
This example demonstrates how to create a basic session and perform simple browser operations:
# Import necessary libraries
from playwright.sync_api import Playwright, sync_playwright
from dotenv import load_dotenv
from lexmount import Lexmount
# First, load environment variables
load_dotenv(override=True)
def run(playwright: Playwright) -> None:
# Initialize Lexmount client
lm = Lexmount() # Automatically reads credentials from environment variables
# Create a session on Lexmount
session = lm.sessions.create()
# Connect to the remote session
chromium = playwright.chromium
browser = chromium.connect_over_cdp(session.connect_url)
context = browser.contexts[0]
page = context.pages[0]
# Execute Playwright actions on the remote browser tab
page.goto("https://dev.lexmount.net/")
page_title = page.title()
assert page_title == "Lexmount Browser - AI-Powered Cloud Browser Service", f"Page title is not 'Lexmount Browser - AI-Powered Cloud Browser Service', it is '{page_title}'"
page.screenshot(path="screenshot.png")
# Close page and browser
page.close()
browser.close()
if __name__ == "__main__":
with sync_playwright() as playwright:
run(playwright)Lightweight Browser Demo (light-demo.py)
This example shows how to use chrome-light-docker mode to efficiently extract web page links:
from playwright.sync_api import Playwright, sync_playwright
from dotenv import load_dotenv
from lexmount import Lexmount
# First, load environment variables
load_dotenv(override=True)
def run(playwright: Playwright) -> None:
"""Demonstrates using chrome-light-docker to extract webpage links"""
print("🔗 News links extraction demo")
# Initialize Lexmount client
lm = Lexmount() # Reads credentials from environment variables
# Create a session with chrome-light-docker
session = lm.sessions.create(browser_mode="chrome-light-docker")
# Connect to the remote session
chromium = playwright.chromium
browser = chromium.connect_over_cdp(session.connect_url)
context = browser.contexts[0]
page = context.pages[0]
# Execute Playwright actions on the remote browser tab
page.goto("https://news.sina.cn/")
# Extract all links
links = page.evaluate('''() => {
return Array.from(document.querySelectorAll('a[href]')).map(a => a.href);
}''')
# Save to file
with open("links.txt", "w", encoding="utf-8") as f:
for link in links:
f.write(link + "\n")
print(f"✅ Extracted {len(links)} links, saved to: links.txt")
# Close page and browser
page.close()
browser.close()
if __name__ == "__main__":
with sync_playwright() as playwright:
run(playwright)Common Issues
Node.js SDK Usage Guide
Quick Access to Examples
You can directly access our JavaScript/TypeScript SDK Quickstart Repository on GitHub for ready-to-use examples.
Prerequisites
Please ensure you have Node.js 14 or higher installed. You can download and install it from the Node.js official website.
1. Install Dependencies
npm install2. Configure Environment Variables
Create a .env file in the project root:
# .env
LEXMOUNT_API_KEY=your_api_key_here
LEXMOUNT_PROJECT_ID=your_project_id_hereGet your credentials from: https://dev.lexmount.net/
3. Run Examples
# Basic demo
npm run demo
# Light browser demo
npm run light-demoExample Code Explanation
Basic Demo (demo.ts)
This example demonstrates how to create a basic session and perform simple browser operations:
/**
* Basic Lexmount Demo
* - Visit Lexmount website
* - Verify page title
* - Take screenshot
*/
import { config } from 'dotenv';
import { chromium } from 'playwright';
import { Lexmount } from 'lexmount';
// Load environment variables
config();
async function main() {
console.log('🚀 Starting Lexmount basic demo...\n');
// Initialize Lexmount client
// Reads LEXMOUNT_API_KEY and LEXMOUNT_PROJECT_ID from environment variables
const lm = new Lexmount();
console.log('📡 Creating browser session...');
// Create a session on Lexmount
const session = await lm.sessions.create();
console.log(`✓ Session created: ${session.sessionId}\n`);
// Connect to the remote session
const browser = await chromium.connectOverCDP(session.connectUrl);
const context = browser.contexts()[0];
const page = context.pages()[0];
// Execute Playwright actions on the remote browser
console.log('🌐 Navigating to Lexmount website...');
await page.goto('https://dev.lexmount.net/');
const pageTitle = await page.title();
console.log(`📄 Page title: ${pageTitle}`);
// Verify the page title
const expectedTitle = 'Lexmount Browser - AI-Powered Cloud Browser Service';
if (pageTitle === expectedTitle) {
console.log('✓ Page title verified!\n');
} else {
throw new Error(
`Page title mismatch!\nExpected: ${expectedTitle}\nActual: ${pageTitle}`
);
}
// Take a screenshot
console.log('📸 Taking screenshot...');
await page.screenshot({ path: 'screenshot.png' });
console.log('✓ Screenshot saved to: screenshot.png\n');
// Clean up
await page.close();
await browser.close();
console.log('✨ Demo completed successfully!');
}
main().catch((error) => {
console.error('❌ Error:', error.message);
process.exit(1);
});Light Browser Demo (light-demo.ts)
This example shows how to use chrome-light-docker mode to efficiently extract web page links:
/**
* Light Browser Demo
* - Use chrome-light-docker mode
* - Visit Sina News
* - Extract all links and save to links.txt
*/
import { config } from 'dotenv';
import { chromium } from 'playwright';
import { Lexmount } from 'lexmount';
import { writeFileSync } from 'fs';
// Load environment variables
config();
async function main() {
console.log('🔗 提取新闻链接演示\n');
// Initialize Lexmount client
const lm = new Lexmount();
console.log('📡 Creating light browser session...');
// Create a session with chrome-light-docker mode
const session = await lm.sessions.create({
browserMode: 'chrome-light-docker',
});
console.log(`✓ Session created: ${session.sessionId}\n`);
// Connect to the remote session
const browser = await chromium.connectOverCDP(session.connectUrl);
const context = browser.contexts()[0];
const page = context.pages()[0];
// Navigate to Sina News
console.log('🌐 Navigating to Sina News...');
await page.goto('https://news.sina.cn/');
console.log('✓ Page loaded\n');
// Extract all links
console.log('🔍 Extracting links...');
const links = await page.evaluate(() => {
return Array.from(document.querySelectorAll('a[href]')).map(
(a) => (a as HTMLAnchorElement).href
);
});
// Save to file
const filename = 'links.txt';
writeFileSync(filename, links.join('\n'), 'utf-8');
console.log(`✅ Extracted ${links.length} links, saved to: ${filename}\n`);
// Clean up
// Note: Commented out to keep session alive for inspection
// await page.close();
// await browser.close();
console.log('✨ Demo completed successfully!');
}
main().catch((error) => {
console.error('❌ Error:', error.message);
process.exit(1);
});Common Issues
Next Steps
- Check out the API Reference for more detailed interface explanations
- Read Advanced Usage to learn about more advanced features
- Visit Example Library for more practical application cases
Got questions?
If you encounter any issues during use, please check the FAQ or Contact Us for support.
Lexmount Docs