### Run a Browser Example Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/README.md This command demonstrates how to execute a Python script from the examples directory. Ensure you are in the root of the SDK project to run this command. ```bash python examples/browsers/start_browser.py ``` -------------------------------- ### Start Browser Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/browsers-service.md Starts a browser instance for a specified profile. This method initiates a single browser session and returns its startup information. ```APIDOC ## POST /browsers/{profile_id} ### Description Starts a browser instance for an existing profile. ### Method POST ### Endpoint /browsers/{profile_id} ### Parameters #### Path Parameters - **profile_id** (str) - Yes - Unique identifier of the profile to start the browser for ### Response #### Success Response (200) API response as `dict[str, Any]` containing browser startup information and status ### Raises `RuntimeError` if the API request fails ``` -------------------------------- ### Start a One-Off Browser with Custom Configuration Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/README.md Start a browser instance with a custom configuration, including proxy, fingerprint, and startup URLs. This is for temporary or specific use cases. ```python # Start a once-off browser with custom configuration config = { "name": "testProfile", "platform": "Windows", "kernelMilestone": "132", "headless": False, "proxy": "http://admin:123456@127.0.0.1:8000", "fingerprint": { "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...", "screen": {"width": 1280, "height": 1024} }, "startupUrls": ["https://www.example.com"] } response = client.browsers.start_once_browser(data=config) ``` -------------------------------- ### Start a Browser Instance Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/README.md Start a single browser instance for a given profile ID. Use this when you need to control one browser at a time. ```python # Start a browser for a specific profile response = client.browsers.start_browser(profile_id="your_profile_id") ``` -------------------------------- ### Start Browser for Profile Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/endpoints.md Starts a browser instance for a specified profile using its unique identifier. Requires authentication via the x-api-key header. ```APIDOC ## POST /browsers/{profile_id} ### Description Starts a browser instance for an existing profile. ### Method POST ### Endpoint /browsers/{profile_id} ### Parameters #### Path Parameters - **profile_id** (string) - Required - Unique identifier of the profile ### Request Body Empty or null ### Response #### Success Response (200) - **code** (integer) - Description - **message** (string) - Description - **data** (object) - Description - **profileId** (string) - Description - **status** (string) - Description - **wsEndpoint** (string) - Description - **pageCount** (integer) - Description - **timestamp** (integer) - Description #### Response Example ```json { "code": 0, "message": "success", "data": { "profileId": "string", "status": "running", "wsEndpoint": "ws://...", "pageCount": 0, "timestamp": 0 } } ``` ``` -------------------------------- ### Install Nstbrowser SDK Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/README.md Install the Nstbrowser SDK using pip. This is the first step to using the SDK in your Python project. ```bash pip install nstbrowser ``` -------------------------------- ### Start Once Browser Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/browsers-service.md Starts a temporary browser instance with custom configuration without creating a persistent profile. Useful for one-time automation tasks. ```APIDOC ## POST /browsers/once ### Description Starts a temporary browser instance with custom configuration without creating a persistent profile. Useful for one-time automation tasks. ### Method POST ### Endpoint /browsers/once ### Parameters #### Request Body - **data** (dict) - Required - Browser configuration object. See configuration details below. ### Request Example ```python { "name": "One-time Browser", "platform": "Windows", "kernelMilestone": "132", "headless": false, "autoClose": true, "timedCloseSec": 300, "proxy": "http://user:pass@proxy.example.com:8080", "fingerprint": { "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "deviceMemory": 8, "hardwareConcurrency": 16, "localization": { "language": "en-US", "timezone": "America/New_York" }, "screen": {"width": 1920, "height": 1080}, "geolocation": { "latitude": "40.7128", "longitude": "-74.0060", "accuracy": "100" } }, "startupUrls": ["https://example.com"], "args": { "--remote-debugging-port": 9222 } } ``` ### Response #### Success Response (200) - **browser_instance_info** (dict) - Information about the started browser instance. - **cdp_endpoint** (str) - The Chrome DevTools Protocol endpoint URL. #### Response Example ```json { "browser_instance_info": { "id": "some-browser-id", "name": "One-time Browser", "status": "running" }, "cdp_endpoint": "ws://localhost:9222/devtools/browser/some-browser-id" } ``` ### Configuration Object Fields #### `data.name` (str, Optional) Display name for the temporary browser instance #### `data.platform` (str, Optional) Operating system: "Windows", "MacOS", or "Linux" #### `data.kernelMilestone` (str, Optional) Chrome kernel version (e.g., "132") #### `data.headless` (bool, Optional, Default: False) Run browser in headless mode without GUI #### `data.incognito` (bool, Optional, Default: False) Start browser in incognito/private mode #### `data.autoClose` (bool, Optional, Default: False) Automatically close browser after task completion #### `data.timedCloseSec` (int, Optional) Auto-close browser after specified seconds #### `data.proxy` (str, Optional) Proxy URL in format "http://user:password@host:port" #### `data.skipProxyChecking` (bool, Optional, Default: False) Skip proxy validation on startup #### `data.fingerprint` (dict, Optional) Browser fingerprinting configuration #### `data.startupUrls` (list[str], Optional) URLs to open when browser starts #### `data.args` (dict, Optional) Chrome command-line arguments ### Fingerprint Configuration (nested object) #### `data.fingerprint.userAgent` (str, Optional) Custom user agent string #### `data.fingerprint.deviceMemory` (int, Optional) Device memory in GB #### `data.fingerprint.hardwareConcurrency` (int, Optional) Number of CPU cores #### `data.fingerprint.disableImageLoading` (bool, Optional) Disable loading of images #### `data.fingerprint.restoreLastSession` (bool, Optional) Restore previous session #### `data.fingerprint.doNotTrack` (bool, Optional) Send Do Not Track header #### `data.fingerprint.localization` (dict, Optional) Language, timezone, and locale settings #### `data.fingerprint.screen` (dict, Optional) Screen resolution with "width" and "height" #### `data.fingerprint.geolocation` (dict, Optional) GPS coordinates with "latitude", "longitude", "accuracy" #### `data.fingerprint.webrtc` (dict, Optional) WebRTC configuration with "publicIp" #### `data.fingerprint.flags` (dict, Optional) Browser flags for fingerprinting behavior ``` -------------------------------- ### Start Browsers (Batch) Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/browsers-service.md Starts browser instances for multiple profiles in a single batch operation. This is efficient for initiating several browser sessions simultaneously. ```APIDOC ## POST /browsers ### Description Starts browser instances for multiple profiles in a batch operation. ### Method POST ### Endpoint /browsers ### Parameters #### Request Body - **profile_ids** (list[str]) - Yes - List of profile IDs to start browsers for ### Response #### Success Response (200) API response as `dict[str, Any]` containing status for each browser start operation ### Raises `RuntimeError` if the API request fails ``` -------------------------------- ### Start a Temporary Browser Instance Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/browsers-service.md Use this method to start a temporary browser instance with custom configurations for one-time automation tasks. It allows for detailed settings like proxy, fingerprinting, and startup URLs. ```python from nstbrowser import NstbrowserClient client = NstbrowserClient(api_key="your_api_key") config = { "name": "One-time Browser", "platform": "Windows", "kernelMilestone": "132", "headless": False, "autoClose": True, "timedCloseSec": 300, "proxy": "http://user:pass@proxy.example.com:8080", "fingerprint": { "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "deviceMemory": 8, "hardwareConcurrency": 16, "localization": { "language": "en-US", "timezone": "America/New_York" }, "screen": {"width": 1920, "height": 1080}, "geolocation": { "latitude": "40.7128", "longitude": "-74.0060", "accuracy": "100" } }, "startupUrls": ["https://example.com"], "args": { "--remote-debugging-port": 9222 } } try: response = client.browsers.start_once_browser(data=config) print("Once-off browser started") print(f"Response: {response}") except RuntimeError as e: print(f"Failed to start once-off browser: {e}") ``` -------------------------------- ### NstbrowserClient Initialization and Basic Usage Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/README.md Demonstrates how to initialize the NstbrowserClient, start and stop a browser, and connect via CDP for automation. ```APIDOC ## NstbrowserClient Initialization and Basic Usage ### Description This section shows how to initialize the NstbrowserClient with an API key, start a browser instance using a profile ID, and then stop the browser instance. It also includes an example of connecting to the browser via the Chrome DevTools Protocol (CDP) for advanced automation tasks, demonstrating how to retrieve the WebSocket debugger URL and use it with a library like Playwright. ### Method Python SDK methods ### Endpoint N/A (SDK methods) ### Parameters #### NstbrowserClient Initialization - **api_key** (string) - Required - Your Nstbrowser API key. #### `client.browsers.start_browser` - **profile_id** (string) - Required - The ID of the profile to use for starting the browser. #### `client.cdp_endpoints.connect_browser` - **profile_id** (string) - Required - The ID of the profile for which to connect via CDP. - **config** (object) - Optional - Configuration options for the browser connection, e.g., `{"headless": False}`. #### `client.browsers.stop_browser` - **profile_id** (string) - Required - The ID of the profile for the browser to stop. ### Request Example ```python from nstbrowser import NstbrowserClient # Initialize client client = NstbrowserClient(api_key="your_api_key") # Start a browser response = client.browsers.start_browser(profile_id="your_profile_id") # Connect via CDP for automation cdp_response = client.cdp_endpoints.connect_browser( profile_id="your_profile_id", config={"headless": False} ) websocket_url = cdp_response["data"]["webSocketDebuggerUrl"] # Use with Playwright from playwright.async_api import async_playwright async with async_playwright() as p: browser = await p.chromium.connect_over_cdp(websocket_url) # ... automation code ... # Stop browser client.browsers.stop_browser(profile_id="your_profile_id") ``` ### Response #### Success Response (`client.browsers.start_browser`) - **data** (object) - Contains information about the started browser. - **status** (string) - Indicates the success status of the operation. #### Success Response (`client.cdp_endpoints.connect_browser`) - **data** (object) - Contains connection details, including `webSocketDebuggerUrl`. - **status** (string) - Indicates the success status of the operation. #### Success Response (`client.browsers.stop_browser`) - **data** (object) - Typically empty or contains confirmation details. - **status** (string) - Indicates the success status of the operation. #### Response Example (`client.cdp_endpoints.connect_browser`) ```json { "data": { "webSocketDebuggerUrl": "ws://127.0.0.1:9222/devtools/browser/some-guid" }, "status": "success" } ``` ``` -------------------------------- ### Start Multiple Browser Instances Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/README.md Start multiple browser instances simultaneously by providing a list of profile IDs. This is useful for batch operations. ```python # Start multiple browsers in batch response = client.browsers.start_browsers(profile_ids=["profile_id_1", "profile_id_2"]) ``` -------------------------------- ### Start Browser for a Profile Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/endpoints.md Use this endpoint to start a browser instance associated with a specific profile. Ensure the profile ID is valid and the API key is correctly provided in the header. ```json { "code": 0, "message": "success", "data": { "profileId": "string", "status": "running", "wsEndpoint": "ws://...", "pageCount": 0, "timestamp": 0 } } ``` -------------------------------- ### Start a Single Browser Instance Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/browsers-service.md Use this method to start a browser for a specific profile. Ensure you have a valid profile ID. The method returns API response details upon success or raises a RuntimeError on failure. ```python from nstbrowser import NstbrowserClient client = NstbrowserClient(api_key="your_api_key") try: response = client.browsers.start_browser(profile_id="d261ff21-9c1c-4832-a003-057e92b691a7") print("Browser started successfully") print(f"Response: {response}") except RuntimeError as e: print(f"Failed to start browser: {e}") ``` -------------------------------- ### Example Success API Response Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/types.md An example of a successful API response, demonstrating the structure with a profile ID, name, and platform. ```json { "code": 0, "message": "success", "data": { "profileId": "d261ff21-9c1c-4832-a003-057e92b691a7", "name": "My Profile", "platform": "Windows" } } ``` -------------------------------- ### Check Browser Availability and Start if Needed Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/cdp-endpoints-service.md Verify if a browser instance is running for a given profile ID. If not running, this snippet starts the browser. It uses a try-except block to handle potential connection errors. ```python from nstbrowser import NstbrowserClient client = NstbrowserClient(api_key="your_api_key") profile_id = "d261ff21-9c1c-4832-a003-057e92b691a7" try: # Try to connect - if browser isn't running, it will fail config = {"headless": False, "autoClose": False} response = client.cdp_endpoints.connect_browser( profile_id=profile_id, config=config ) print("Browser is running") except RuntimeError as e: print("Browser is not running, starting it...") client.browsers.start_browser(profile_id=profile_id) ``` -------------------------------- ### Initialize Client and Use Service Modules Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/nstbrowser-client.md Demonstrates how to initialize the NstbrowserClient with an API key and use its service modules to start a browser and create a profile. Includes basic error handling for API requests. ```python from nstbrowser import NstbrowserClient import os # Initialize client api_key = os.environ.get("NSTBROWSER_API_KEY", "your_api_key") client = NstbrowserClient(api_key=api_key) # Use service modules try: # Start a browser response = client.browsers.start_browser(profile_id="profile_id_123") print("Browser started:", response) # Create a profile profile_data = { "name": "My Profile", "platform": "Windows", "kernelMilestone": "132" } response = client.profiles.create_profile(data=profile_data) print("Profile created:", response) except RuntimeError as e: print(f"API Error: {e}") ``` -------------------------------- ### Example Error API Response Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/types.md An example of an API error response, showing an error code, message, and null data. ```json { "code": 400, "message": "Invalid profile ID format", "data": null } ``` -------------------------------- ### Start Once-Off Browser Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/endpoints.md Launches a temporary browser instance with custom configurations, suitable for single-use scenarios without persistent profiles. Requires API key authentication. ```APIDOC ## POST /browsers/once ### Description Starts a temporary browser with custom configuration without creating a persistent profile. ### Method POST ### Endpoint /browsers/once ### Request Body ```json { "name": "string", "platform": "Windows|MacOS|Linux", "kernelMilestone": "132", "headless": false, "incognito": false, "autoClose": false, "timedCloseSec": 300, "proxy": "http://user:pass@host:port", "skipProxyChecking": false, "fingerprint": { "userAgent": "string", "deviceMemory": 8, "hardwareConcurrency": 16, "disableImageLoading": false, "restoreLastSession": false, "doNotTrack": false, "localization": { "language": "string", "languages": ["string"], "timezone": "string" }, "screen": { "width": 1920, "height": 1080 }, "geolocation": { "latitude": "string", "longitude": "string", "accuracy": "string" }, "webrtc": { "publicIp": "string" }, "flags": { "audio": "string", "battery": "string", "canvas": "string", "clientRect": "string", "fonts": "string", "geolocation": "string", "gpu": "string", "localization": "string", "screen": "string", "speech": "string", "timezone": "string", "webgl": "string", "webrtc": "string" } }, "startupUrls": ["string"], "args": { "key": "value" } } ``` ### Response #### Success Response (200) - **code** (integer) - Description - **message** (string) - Description - **data** (object) - Description - **instanceId** (string) - Description - **wsEndpoint** (string) - Description - **status** (string) - Description #### Response Example ```json { "code": 0, "message": "success", "data": { "instanceId": "string", "wsEndpoint": "ws://...", "status": "running" } } ``` ``` -------------------------------- ### Start Multiple Browsers Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/endpoints.md Initiate multiple browser instances simultaneously by providing a list of profile IDs. This is useful for batch operations. ```json [ "profile_id_1", "profile_id_2", "profile_id_3" ] ``` ```json { "code": 0, "message": "success", "data": [ { "profileId": "profile_id_1", "status": "running" }, { "profileId": "profile_id_2", "status": "running" } ] } ``` -------------------------------- ### Example Once-Off Browser Configuration Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/configuration.md This configuration is used to set up a temporary browser instance with specific settings for name, platform, kernel version, headless mode, incognito, auto-close behavior, proxy, fingerprinting details, startup URLs, and Chrome arguments. ```python once_off_config = { "name": "Temporary Browser", "platform": "Windows", "kernelMilestone": "132", "headless": False, "incognito": False, "autoClose": True, "timedCloseSec": 300, "proxy": "http://user:pass@proxy.example.com:8080", "skipProxyChecking": False, "fingerprint": { "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "deviceMemory": 8, "hardwareConcurrency": 16, "disableImageLoading": False, "restoreLastSession": False, "doNotTrack": True, "localization": { "language": "en-US", "languages": ["en-US", "en"], "timezone": "America/New_York" }, "screen": { "width": 1920, "height": 1080 }, "geolocation": { "latitude": "40.7128", "longitude": "-74.0060", "accuracy": "100" }, "webrtc": { "publicIp": "203.0.113.5" }, "flags": { "audio": "Noise", "battery": "Masked", "canvas": "Noise", "clientRect": "Noise", "fonts": "Masked", "geolocation": "Custom", "geolocationPopup": "Prompt", "gpu": "Allow", "localization": "Custom", "screen": "Custom", "speech": "Masked", "timezone": "Custom", "webgl": "Noise", "webrtc": "Custom" } }, "startupUrls": ["https://example.com"], "args": { "--remote-debugging-port": 9222, "--disable-blink-features": "AutomationControlled", "--disable-dev-shm-usage": True } } ``` -------------------------------- ### Set Environment Variables for SDK Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/configuration.md Example of setting environment variables in a .env file for NSTBrowser SDK configuration. ```bash # .env file export NSTBROWSER_API_KEY=your_api_key_here export NSTBROWSER_API_ADDRESS=http://localhost:8848/api/v2 ``` -------------------------------- ### Connect to a One-Off Browser using CDP Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/README.md Connect to a browser instance started on-the-fly using CDP. This is useful for temporary automation tasks without pre-existing profiles. ```python # Connect to a once-off browser using CDP config = { "name": "testProfile", "platform": "Windows", "kernelMilestone": "132", "autoClose": False, "headless": False } response = client.cdp_endpoints.connect_once_browser(config=config) ``` -------------------------------- ### Start a Once-Off Browser Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/endpoints.md Launch a temporary browser instance with custom configurations without creating a persistent profile. This endpoint allows fine-grained control over browser settings. ```json { "name": "string", "platform": "Windows|MacOS|Linux", "kernelMilestone": "132", "headless": false, "incognito": false, "autoClose": false, "timedCloseSec": 300, "proxy": "http://user:pass@host:port", "skipProxyChecking": false, "fingerprint": { "userAgent": "string", "deviceMemory": 8, "hardwareConcurrency": 16, "disableImageLoading": false, "restoreLastSession": false, "doNotTrack": false, "localization": { "language": "string", "languages": ["string"], "timezone": "string" }, "screen": { "width": 1920, "height": 1080 }, "geolocation": { "latitude": "string", "longitude": "string", "accuracy": "string" }, "webrtc": { "publicIp": "string" }, "flags": { "audio": "string", "battery": "string", "canvas": "string", "clientRect": "string", "fonts": "string", "geolocation": "string", "gpu": "string", "localization": "string", "screen": "string", "speech": "string", "timezone": "string", "webgl": "string", "webrtc": "string" } }, "startupUrls": ["string"], "args": { "key": "value" } } ``` ```json { "code": 0, "message": "success", "data": { "instanceId": "string", "wsEndpoint": "ws://...", "status": "running" } } ``` -------------------------------- ### Get Browsers Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/endpoints.md Retrieves a list of browser instances, with an option to filter by status. ```APIDOC ## GET /browsers ### Description Retrieves list of browser instances with optional filtering. ### Method GET ### Endpoint /browsers ### Parameters #### Query Parameters - **status** (string) - Optional - Filter by status (running, stopped, etc.) ### Response #### Success Response (200) - **code** (integer) - Description - **message** (string) - Description - **data** (array) - Description - **profileId** (string) - Description - **status** (string) - Description - **pageCount** (integer) - Description - **timestamp** (integer) - Description #### Response Example ```json { "code": 0, "message": "success", "data": [ { "profileId": "string", "status": "running", "pageCount": 0, "timestamp": 0 } ] } ``` ``` -------------------------------- ### Browser Endpoints Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/MANIFEST.md Endpoints for managing browser instances, including starting, stopping, and retrieving information about browsers. ```APIDOC ## POST /browsers/{profile_id} ### Description Start a browser instance associated with a specific profile. ### Method POST ### Endpoint /browsers/{profile_id} ## POST /browsers ### Description Start multiple browser instances. ### Method POST ### Endpoint /browsers ## POST /browsers/once ### Description Start a single, once-off browser instance without persistent profile association. ### Method POST ### Endpoint /browsers/once ## DELETE /browsers/{profile_id} ### Description Stop a running browser instance identified by its profile ID. ### Method DELETE ### Endpoint /browsers/{profile_id} ## DELETE /browsers ### Description Stop multiple running browser instances. ### Method DELETE ### Endpoint /browsers ## GET /browsers ### Description List all currently running browser instances. ### Method GET ### Endpoint /browsers ## GET /browsers/{profile_id}/pages ### Description Retrieve a list of all open pages within a specific browser instance. ### Method GET ### Endpoint /browsers/{profile_id}/pages ## GET /browsers/{profile_id}/debugger ### Description Get debugger information for a specific browser instance. ### Method GET ### Endpoint /browsers/{profile_id}/debugger ``` -------------------------------- ### Browser Lifecycle Management Workflow Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/browsers-service.md This snippet shows the complete process of starting a browser, retrieving its pages and debugger info, and then stopping it. Ensure you have your API key and profile ID configured. ```python from nstbrowser import NstbrowserClient import time client = NstbrowserClient(api_key="your_api_key") profile_id = "your_profile_id" try: # 1. Start a browser print("Starting browser...") start_response = client.browsers.start_browser(profile_id=profile_id) print(f"Started: {start_response}") # 2. Wait for browser to be ready time.sleep(2) # 3. Get browser pages print("Getting open pages...") pages = client.browsers.get_browser_pages(profile_id=profile_id) print(f"Pages: {pages}") # 4. Get debugger info for CDP connection print("Getting debugger info...") debugger = client.browsers.get_browser_debugger(profile_id=profile_id) print(f"Debugger: {debugger}") # 5. Stop the browser print("Stopping browser...") stop_response = client.browsers.stop_browser(profile_id=profile_id) print(f"Stopped: {stop_response}") except RuntimeError as e: print(f"Error during browser operations: {e}") ``` -------------------------------- ### Connect Browser CDP Configuration Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/endpoints.md Example JSON configuration for connecting to a profile's browser via CDP. Set `headless` to `true` for background operation. ```json { "headless": false, "autoClose": false, "timedCloseSec": 300, "incognito": false, "skipProxyChecking": false } ``` -------------------------------- ### Connect Once Browser CDP Configuration Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/endpoints.md Example JSON configuration for establishing a CDP connection to a temporary browser instance. Supports detailed customization of browser and connection settings. ```json { "name": "string", "platform": "string", "kernelMilestone": "string", "headless": false, "autoClose": false, "proxy": "string", "fingerprint": {}, "startupUrls": ["string"], "args": {} } ``` -------------------------------- ### Proxy URL Formats Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/configuration.md Examples of different proxy URL formats, including HTTP, HTTPS, SOCKS5, and SOCKS4, with and without authentication. ```python # Basic HTTP proxy proxy_url = "http://proxy.example.com:8080" ``` ```python # HTTP proxy with credentials proxy_url = "http://user:password@proxy.example.com:8080" ``` ```python # SOCKS5 proxy proxy_url = "socks5://proxy.example.com:1080" ``` ```python # SOCKS5 proxy with credentials proxy_url = "socks5://user:password@proxy.example.com:1080" ``` -------------------------------- ### Example Chrome Arguments Configuration Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/configuration.md This snippet shows how to configure common Chrome command-line arguments. Use these arguments to control browser behavior, disable features, and optimize for environments like Docker. ```python args = { "--remote-debugging-port": 34543, "--disable-blink-features": "AutomationControlled", "--disable-dev-shm-usage": True, "--disable-sync": True, "--disable-extensions": True, "--no-first-run": True } ``` -------------------------------- ### Start Browser and Connect with CDP Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/README.md Initiates a browser instance using a profile ID and retrieves the WebSocket URL for Chrome DevTools Protocol (CDP) connection. Ensure the profile is created and its ID is available. ```python # Start browser client.browsers.start_browser(profile_id=profile_id) # Get CDP endpoint response = client.cdp_endpoints.connect_browser( profile_id=profile_id, config={"headless": False, "autoClose": False} ) ws_url = response["data"]["webSocketDebuggerUrl"] ``` -------------------------------- ### Basic Nstbrowser SDK Usage in Python Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/README.md Initialize the Nstbrowser client, start a browser instance, connect via Chrome DevTools Protocol (CDP), and stop the browser. This snippet demonstrates the fundamental workflow for interacting with the SDK. ```python from nstbrowser import NstbrowserClient # Initialize client client = NstbrowserClient(api_key="your_api_key") # Start a browser response = client.browsers.start_browser(profile_id="your_profile_id") # Connect via CDP for automation cdp_response = client.cdp_endpoints.connect_browser( profile_id="your_profile_id", config={"headless": False} ) websocket_url = cdp_response["data"]["webSocketDebuggerUrl"] # Use with Playwright from playwright.async_api import async_playwright async with async_playwright() as p: browser = await p.chromium.connect_over_cdp(websocket_url) # ... automation code ... # Stop browser client.browsers.stop_browser(profile_id="your_profile_id") ``` -------------------------------- ### connect_once_browser Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/cdp-endpoints-service.md Establishes a Chrome DevTools Protocol connection to a temporary browser instance created with custom configuration. This starts a new browser session without using a saved profile. ```APIDOC ## GET /connect ### Description Establishes a Chrome DevTools Protocol connection to a temporary browser instance created with custom configuration. This starts a new browser session without using a saved profile. ### Method GET ### Endpoint /connect ### Parameters #### Query Parameters - **config** (dict) - Required - Complete browser and connection configuration object ### Request Body This section is not applicable as parameters are passed via query string. ### Response #### Success Response (200) - **data** (dict) - Contains CDP endpoint URLs and debugger information - **webSocketDebuggerUrl** (str) - The WebSocket URL for the CDP connection #### Response Example ```json { "data": { "webSocketDebuggerUrl": "ws://localhost:9222/devtools/browser/some-guid" } } ``` ### Configuration Object Details: This object combines browser configuration and connection settings. | Field | Type | Required | Description | |---|---|---|---| | `name` | str | No | Display name for the temporary instance | | `platform` | str | No | Operating system: "Windows", "MacOS", or "Linux" | | `kernelMilestone` | str | No | Chrome kernel version (e.g., "132") | | `headless` | bool | No | Run browser in headless mode | | `incognito` | bool | No | Start in incognito mode | | `autoClose` | bool | No | Automatically close when connection ends | | `timedCloseSec` | int | No | Auto-close after specified seconds | | `proxy` | str | No | Proxy URL: "http://user:password@host:port" | | `skipProxyChecking` | bool | No | Skip proxy validation | | `fingerprint` | dict | No | Browser fingerprinting configuration | | `startupUrls` | list[str] | No | URLs to open on startup | | `args` | dict | No | Chrome command-line arguments | ### Fingerprint Configuration (nested object): | Field | Type | Description | |---|---|---| | `userAgent` | str | Custom user agent string | | `deviceMemory` | int | Device memory in GB | | `hardwareConcurrency` | int | Number of CPU cores | | `disableImageLoading` | bool | Disable image loading | | `doNotTrack` | bool | Send Do Not Track header | | `localization` | dict | Language, timezone settings | | `screen` | dict | Screen resolution with "width" and "height" | | `geolocation` | dict | GPS coordinates with "latitude", "longitude", "accuracy" | | `webrtc` | dict | WebRTC configuration with "publicIp" | | `flags` | dict | Browser fingerprinting behavior flags | ### Raises - `RuntimeError` if the API request fails ``` -------------------------------- ### Async Playwright Example with Existing Profile Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/cdp-endpoints-service.md Connect to an existing browser profile via CDP and control it using Playwright's asynchronous API. This is useful for automating tasks in a pre-configured browser environment. ```python import asyncio import os from nstbrowser import NstbrowserClient from playwright.async_api import async_playwright async def main(): # Initialize Nstbrowser client api_key = os.environ.get("NSTBROWSER_API_KEY", "your_api_key") nst_client = NstbrowserClient(api_key=api_key) profile_id = "d261ff21-9c1c-4832-a003-057e92b691a7" # Get CDP WebSocket URL config = {"headless": False, "autoClose": False} response = nst_client.cdp_endpoints.connect_browser( profile_id=profile_id, config=config ) ws_url = response["data"]["webSocketDebuggerUrl"] print(f"Connected to CDP: {ws_url}") # Use Playwright to automate async with async_playwright() as p: browser = await p.chromium.connect_over_cdp(ws_url) # Get default context and page context = browser.contexts[0] pages = context.pages page = pages[0] if pages else await context.new_page() # Perform automation print("Navigating to example.com...") await page.goto("https://example.com") title = await page.title() print(f"Page title: {title}") await page.screenshot(path="screenshot.png") await page.close() await browser.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Once-Off Browser with Playwright Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/cdp-endpoints-service.md Start a temporary browser instance with custom configurations and automate it using Playwright's asynchronous API. This is suitable for short-lived, isolated automation tasks. ```python import asyncio from nstbrowser import NstbrowserClient from playwright.async_api import async_playwright async def main(): api_key = "your_api_key" nst_client = NstbrowserClient(api_key=api_key) # Start temporary browser with custom config config = { "name": "Temp Automation", "platform": "Windows", "kernelMilestone": "132", "headless": False, "autoClose": False, "fingerprint": { "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" } } response = nst_client.cdp_endpoints.connect_once_browser(config=config) ws_url = response["data"]["webSocketDebuggerUrl"] # Connect and automate with Playwright async with async_playwright() as p: browser = await p.chromium.connect_over_cdp(ws_url) page = browser.contexts[0].pages[0] await page.goto("https://httpbin.org/headers") headers = await page.text_content("body") print("Request headers:", headers) await browser.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Prepare Profile for Automation Task Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/locals-service.md Prepares a profile for a fresh automation run by clearing previous session data. This ensures that the automation task starts with a clean slate. ```python from nstbrowser import NstbrowserClient client = NstbrowserClient(api_key="your_api_key") def prepare_profile_for_automation(profile_id: str) -> bool: """Prepare a profile for a fresh automation run.""" try: print(f"Preparing profile {profile_id} for automation...") # Clear previous session data client.locals.clear_profile_cache(profile_id=profile_id) client.locals.clear_profile_cookies(profile_id=profile_id) # Now start the browser for automation response = client.browsers.start_browser(profile_id=profile_id) print("Profile ready for automation") return True except RuntimeError as e: print(f"Failed to prepare profile: {e}") return False ``` -------------------------------- ### Get Browser Profiles with Filtering Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/README.md Retrieve a list of existing browser profiles, with options for pagination and filtering. This helps in managing and selecting profiles. ```python # Get profiles with filtering response = client.profiles.get_profiles(data={"page": 1, "pageSize": 10}) ``` -------------------------------- ### Example Debug Log Output Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/errors.md This shows the typical output seen in debug logs when using the nstbrowser SDK, including the POST request details and any errors encountered during the operation. ```text DEBUG:nstbrowser.client:POST Request URL: http://localhost:8848/api/v2/browsers/profile_123, kwargs: {} ERROR:nstbrowser.client:Error in [BrowsersService.start_browser]: ... ``` -------------------------------- ### Ensure Browser Resource Cleanup Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/configuration.md Starts a browser, performs operations, and ensures the browser is stopped using a try-finally block for guaranteed cleanup. Handles potential exceptions during stop_browser. ```python client = NstbrowserClient(api_key="your_api_key") profile_id = "profile_123" try: client.browsers.start_browser(profile_id=profile_id) # ... perform operations ... finally: try: client.browsers.stop_browser(profile_id=profile_id) except Exception: pass ``` -------------------------------- ### Handling 500 Internal Server Errors with Retries Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/errors.md This example demonstrates a robust strategy for handling 500 Internal Server Errors by implementing a retry mechanism with exponential backoff. This approach helps mitigate transient server issues. ```python import time client = NstbrowserClient(api_key="your_api_key") def retry_with_backoff(func, max_retries=3): """Retry a function with exponential backoff for server errors.""" for attempt in range(max_retries): try: return func() except RuntimeError as e: if "500" in str(e) and attempt < max_retries - 1: wait_time = 2 ** attempt # Exponential backoff print(f"Server error, retrying in {wait_time}s...") time.sleep(wait_time) else: raise try: result = retry_with_backoff( lambda: client.browsers.get_browsers() ) except RuntimeError as e: print(f"Failed after retries: {e}") ``` -------------------------------- ### Selective Error Handling for Browser Start Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/errors.md Use this pattern to catch specific RuntimeErrors and provide tailored responses based on error messages, such as 404 for missing profiles or 401 for authentication issues. ```python from nstbrowser import NstbrowserClient client = NstbrowserClient(api_key="your_api_key") try: # Try to start browser client.browsers.start_browser(profile_id="profile_123") except RuntimeError as e: error_msg = str(e) if "404" in error_msg or "not found" in error_msg.lower(): print("Profile does not exist") # Handle missing profile elif "401" in error_msg or "unauthorized" in error_msg.lower(): print("API key is invalid") # Handle authentication error elif "400" in error_msg: print("Invalid request parameters") # Handle validation error elif "500" in error_msg: print("Server error, please retry later") # Handle server error else: print(f"Unexpected error: {e}") # Handle other errors ``` -------------------------------- ### Get CDP WebSocket URL and Automate with Playwright Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/README.md Obtain the CDP WebSocket URL from the client and then use it to connect Playwright for browser automation. Ensure the Playwright library is installed. ```python # Get the CDP WebSocket URL websocket_url = client.cdp_endpoints.connect_browser( profile_id="your_profile_id", config={"headless": False} )["data"]["webSocketDebuggerUrl"] # Use the URL with Playwright for automation from playwright.async_api import async_playwright async def automate(): async with async_playwright() as p: browser = await p.chromium.connect_over_cdp(websocket_url) page = browser.contexts[0].pages[0] await page.goto("https://example.com") # ... perform other actions ``` -------------------------------- ### Complete Browser Automation Workflow Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/api-reference/cdp-endpoints-service.md Orchestrates a full browser automation workflow: starting the browser, connecting via CDP, performing automation tasks (placeholder), and finally stopping the browser. Includes error handling and cleanup. ```python from nstbrowser import NstbrowserClient import time client = NstbrowserClient(api_key="your_api_key") profile_id = "d261ff21-9c1c-4832-a003-057e92b691a7" try: # 1. Start browser print("Starting browser...") client.browsers.start_browser(profile_id=profile_id) time.sleep(2) # 2. Connect via CDP print("Connecting via CDP...") config = {"headless": False, "autoClose": False} response = client.cdp_endpoints.connect_browser( profile_id=profile_id, config=config ) ws_url = response["data"]["webSocketDebuggerUrl"] # 3. Use with Playwright (see examples above) # ... automation code ... # 4. Stop browser print("Stopping browser...") client.browsers.stop_browser(profile_id=profile_id) except RuntimeError as e: print(f"Error: {e}") # Cleanup if needed try: client.browsers.stop_browser(profile_id=profile_id) except: pass ``` -------------------------------- ### Batch Operations for Browsers and Proxies Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/README.md Enables performing operations on multiple browser profiles simultaneously, such as starting several browsers or updating proxy configurations for multiple profiles in a single request. ```python # Start multiple browsers profile_ids = ["id1", "id2", "id3"] client.browsers.start_browsers(profile_ids=profile_ids) # Update proxies for multiple profiles batch_data = { "profile_1": {"url": "http://proxy1:8080"}, "profile_2": {"url": "http://proxy2:8080"} } client.profiles.batch_update_proxy(data=batch_data) ``` -------------------------------- ### Handling 401 Unauthorized Errors Source: https://github.com/nstbrowser/nstbrowser-sdk-python/blob/main/_autodocs/errors.md This example shows how to catch a RuntimeError for a 401 Unauthorized status, typically caused by an invalid or expired API key. Always verify your API key is correctly configured and has the necessary permissions. ```python from nstbrowser import NstbrowserClient try: # Using invalid API key client = NstbrowserClient(api_key="invalid_key_123") response = client.browsers.get_browsers() except RuntimeError as e: print(f"Authentication failed: {e}") ```