### Install Hyperbrowser SDK Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md Install the Hyperbrowser SDK from PyPI. This command is used to add the library to your Python environment. ```shell pip install hyperbrowser ``` -------------------------------- ### Install Dependencies with Poetry Source: https://github.com/hyperbrowserai/python-sdk/blob/main/CLAUDE.md Installs project dependencies using Poetry. Ensure Poetry is installed and configured for the project. ```bash poetry install ``` -------------------------------- ### Start Sandbox from Memory Snapshot Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates a new sandbox environment by restoring it from a previously saved memory snapshot. Requires a valid snapshot ID. ```python restored = client.sandboxes.start_from_snapshot( StartSandboxFromSnapshotParams(snapshot_id=snapshot.id) ) ``` -------------------------------- ### Async Client Full Example - Hyperbrowser SDK Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Use this snippet to perform parallel scrape and crawl operations, and to interact with AI agents. Ensure you have the necessary imports and an API key. ```python import asyncio from hyperbrowser import AsyncHyperbrowser from hyperbrowser.models import ( StartScrapeJobParams, ScrapeOptions, StartCrawlJobParams, StartExtractJobParams, StartBrowserUseTaskParams, ) async def main(): async with AsyncHyperbrowser(api_key="your-api-key") as client: # Parallel scrape + crawl scrape_task = asyncio.create_task( client.scrape.start_and_wait( StartScrapeJobParams( url="https://example.com", scrape_options=ScrapeOptions(formats=["markdown"]), ) ) ) crawl_task = asyncio.create_task( client.crawl.start_and_wait( StartCrawlJobParams(url="https://docs.example.com", max_pages=5) ) ) scrape_result, crawl_result = await asyncio.gather(scrape_task, crawl_task) print(scrape_result.data.markdown[:200]) print(f"Crawled {crawl_result.total_crawled_pages} pages") # AI agent agent_result = await client.agents.browser_use.start_and_wait( StartBrowserUseTaskParams(task="Find the top post on news.ycombinator.com") ) print(agent_result.result) asyncio.run(main()) ``` -------------------------------- ### Mount Volume in Sandbox Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Creates a new sandbox and mounts a persistent volume into it with read-write permissions, configured to be shared across multiple sandboxes. The example then executes a command within the sandbox to verify the mount. ```python # Mount volume in a sandbox (read-write, shared across sandboxes) sandbox = client.sandboxes.create( CreateSandboxParams( image_name="node", mounts={ "/workspace/cache": SandboxVolumeMount( id=volume.id, type="rw", shared=True, ) }, ) ) sandbox.exec("ls /workspace/cache") sandbox.stop() client.close() ``` -------------------------------- ### Volume Management Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Create, list, get, and mount persistent cloud volumes for sandbox environments. ```APIDOC ## Volumes — `client.volumes` Creating and managing persistent cloud volumes that can be mounted into sandbox environments for shared or durable storage. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateVolumeParams, CreateSandboxParams, SandboxVolumeMount client = Hyperbrowser(api_key="your-api-key") # Create a named volume volume = client.volumes.create(CreateVolumeParams(name="project-cache")) print(volume.id) # "vol_abc123" print(volume.name) # "project-cache" # List all volumes all_volumes = client.volumes.list() for v in all_volumes.volumes: print(v.id, v.name) # Get a specific volume v = client.volumes.get(volume.id) # Mount volume in a sandbox (read-write, shared across sandboxes) sandbox = client.sandboxes.create( CreateSandboxParams( image_name="node", mounts={ "/workspace/cache": SandboxVolumeMount( id=volume.id, type="rw", shared=True, ) }, ) ) sandbox.exec("ls /workspace/cache") sandbox.stop() client.close() ``` ``` -------------------------------- ### Sync Browser Session Usage Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md Create and manage a synchronous browser session. This example shows how to connect using Playwright, navigate to a URL, and get the page title. The `HYPERBROWSER_API_KEY` must be configured. ```python from playwright.sync_api import sync_playwright from hyperbrowser import Hyperbrowser HYPERBROWSER_API_KEY = "test-key" def main(): client = Hyperbrowser(api_key=HYPERBROWSER_API_KEY) session = client.sessions.create() ws_endpoint = session.ws_endpoint # Launch Playwright and connect to the remote browser with sync_playwright() as p: browser = p.chromium.connect_over_cdp(ws_endpoint) context = browser.new_context() # Get the first page or create a new one if len(context.pages) == 0: page = context.new_page() else: page = context.pages[0] # Navigate to a website print("Navigating to Hacker News...") page.goto("https://news.ycombinator.com/") page_title = page.title() print("Page title:", page_title) page.close() browser.close() print("Session completed!") client.sessions.stop(session.id) # Run the asyncio event loop main() ``` -------------------------------- ### Start Non-blocking BrowserUse Task with Stop Support Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Starts a BrowserUse agent task asynchronously and allows for stopping the task using its job ID. Includes a loop to poll for status updates. ```python job = client.agents.browser_use.start( StartBrowserUseTaskParams(task="Search for Python async tutorials on DuckDuckGo") ) print(f"Task started: {job.job_id}") import time for _ in range(60): status = client.agents.browser_use.get_status(job.job_id) if status.status in ("completed", "failed", "stopped"): break time.sleep(5) final = client.agents.browser_use.get(job.job_id) print(final.result) # Stop a running task client.agents.browser_use.stop(job.job_id) ``` -------------------------------- ### Start and Wait for Gemini Computer Use Agent Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates a Gemini computer use agent task and waits for its completion. Requires specifying the task and maximum number of steps. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartGeminiComputerUseTaskParams client = Hyperbrowser(api_key="your-api-key") result = client.agents.gemini_computer_use.start_and_wait( StartGeminiComputerUseTaskParams( task="Go to weather.com and find the current weather for New York City.", max_steps=10, ) ) print(result.status) print(result.result) ``` -------------------------------- ### Start Batch Fetch Job with Markdown and Screenshots Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Executes a batch fetch job for a list of URLs, requesting both Markdown content and screenshots for each page. The job runs and waits for completion, then prints status and data for each fetched URL. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import ( StartBatchFetchJobParams, FetchOutputFormats, FetchOutputMarkdown, FetchOutputScreenshot, ) client = Hyperbrowser(api_key="your-api-key") result = client.web.batch_fetch.start_and_wait( StartBatchFetchJobParams( urls=[ "https://example.com", "https://example.org", "https://python.org", ], outputs=FetchOutputFormats( formats=[FetchOutputMarkdown(), FetchOutputScreenshot()] ), ) ) print(result.status) print(result.total_pages) for page in result.data: print(page.url, page.status) if page.markdown: print(page.markdown[:300]) if page.screenshot: print(f"Screenshot (base64 len): {len(page.screenshot)}") ``` -------------------------------- ### Start and Wait for BrowserUse Task with Schema Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates a BrowserUse agent task and waits for it to complete, returning structured data based on the provided output model schema. Requires defining Pydantic models for the expected output. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartBrowserUseTaskParams from pydantic import BaseModel from typing import List client = Hyperbrowser(api_key="your-api-key") class SearchResult(BaseModel): title: str url: str snippet: str class SearchResults(BaseModel): results: List[SearchResult] result = client.agents.browser_use.start_and_wait( StartBrowserUseTaskParams( task="Go to Hacker News and return the top 5 story titles and URLs.", output_model_schema=SearchResults, max_steps=20, ) ) print(result.status) # "completed" print(result.data) # parsed SearchResults JSON ``` -------------------------------- ### Start and Wait for Extraction Job Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates an extraction job and waits for its completion. Use this for tasks where immediate results are needed. ```python result2 = client.extract.start_and_wait( StartExtractJobParams( urls=[ "https://news.ycombinator.com/", "https://techcrunch.com/", ], prompt="Extract the top 3 article titles and their URLs.", ) ) print(result2.data) ``` -------------------------------- ### Start, Poll, and Get Single-Page Scrape Job Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Starts a non-blocking scrape job for a single URL and then polls for its status before retrieving the final results. Requires manual status checking and polling. ```python # Non-blocking: start → poll → get job = client.scrape.start(StartScrapeJobParams(url="https://example.com")) import time while True: status = client.scrape.get_status(job.job_id) if status.status in ("completed", "failed"): break time.sleep(2) final = client.scrape.get(job.job_id) print(final.data.html[:500]) ``` -------------------------------- ### Start and Wait for HyperAgent Task Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates a HyperAgent task and waits for its completion, returning status, natural language results, and potentially structured data. Use for complex multi-step tasks. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartHyperAgentTaskParams client = Hyperbrowser(api_key="your-api-key") result = client.agents.hyper_agent.start_and_wait( StartHyperAgentTaskParams( task="Go to github.com/trending, find the top trending Python repo today, and return its name, description, and star count.", max_steps=30, ) ) print(result.status) # "completed" print(result.result) # natural language answer print(result.data) # structured data if available ``` -------------------------------- ### Start Non-blocking Claude Computer Use Agent Task Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Starts a Claude Computer Use Agent task without waiting for completion. Allows for checking status and retrieving results later using the job ID. Includes a polling loop. ```python job = client.agents.claude_computer_use.start( StartClaudeComputerUseTaskParams(task="Open reddit.com and find the top post in r/programming today.") ) import time while True: s = client.agents.claude_computer_use.get_status(job.job_id) if s.status in ("completed", "failed", "stopped"): break time.sleep(3) final = client.agents.claude_computer_use.get(job.job_id) print(final.result) ``` -------------------------------- ### Sandbox Operations Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Manage sandboxes, including listing images, snapshots, starting from snapshots, connecting to existing sandboxes, and stopping sandboxes. ```APIDOC ## Sandbox Operations ### List available images ```python images = client.sandboxes.list_images() for img in images.images: print(img.name) ``` ### List snapshots for an image ```python snapshots = client.sandboxes.list_snapshots( SandboxSnapshotListParams(image_name="node", status="created", limit=5) ) ``` ### Start sandbox from a memory snapshot ```python restored = client.sandboxes.start_from_snapshot( StartSandboxFromSnapshotParams(snapshot_id=snapshot.id) ) ``` ### Connect to an existing sandbox by ID ```python existing = client.sandboxes.connect("snd_existing123") print(existing.status) ``` ### Stop the sandbox ```python sandbox.stop() client.close() ``` ``` -------------------------------- ### Start and Stop CUA Agent Task Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Starts a CUA agent task and demonstrates how to stop a running task using its job ID. Useful for managing long-running or unwanted tasks. ```python job = client.agents.cua.start(StartCuaTaskParams(task="Search something on Google.")) client.agents.cua.stop(job.job_id) ``` -------------------------------- ### Start, Poll, and Stream Crawl Job Batches Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Starts a non-blocking crawl job and then polls for its status. Once completed, it retrieves the first batch of crawled page data, showing total pages and batches. ```python # Non-blocking crawl with streaming page batches job = client.crawl.start(StartCrawlJobParams(url="https://docs.example.com", max_pages=100)) print(f"Crawl job started: {job.job_id}") import time while True: status = client.crawl.get_status(job.job_id) if status.status in ("completed", "failed"): break time.sleep(3) # Retrieve first page batch page_resp = client.crawl.get(job.job_id) print(f"Crawled {page_resp.total_crawled_pages} pages across {page_resp.total_page_batches} batches") ``` -------------------------------- ### Start and Wait for Batch Scrape Job Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates and waits for a batch scrape job to complete, processing multiple URLs simultaneously and extracting markdown content from each. ```python # Batch scrape multiple URLs batch = client.scrape.batch.start_and_wait( StartBatchScrapeJobParams( urls=[ "https://example.com", "https://example.org", "https://example.net", ], scrape_options=ScrapeOptions(formats=["markdown"]), ) ) print(batch.total_scraped_pages) # 3 for page in batch.data: print(page.url, page.status, len(page.markdown or "")) ``` -------------------------------- ### Start and Wait for CUA Agent Task Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates a Computer Use Agent (CUA) task and waits for its completion. This agent is compatible with OpenAI's computer control task formats. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartCuaTaskParams client = Hyperbrowser(api_key="your-api-key") result = client.agents.cua.start_and_wait( StartCuaTaskParams( task="Go to news.ycombinator.com and return the titles of the first 10 posts.", max_steps=20, ) ) print(result.status) print(result.result) ``` -------------------------------- ### Start and Wait for Claude Computer Use Agent Task Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates a task for the Claude Computer Use Agent and waits for its completion. This agent uses Anthropic's Claude model for browser automation. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartClaudeComputerUseTaskParams client = Hyperbrowser(api_key="your-api-key") result = client.agents.claude_computer_use.start_and_wait( StartClaudeComputerUseTaskParams( task="Navigate to wikipedia.org, search for 'Python programming language', and return the first paragraph of the article.", max_steps=15, ) ) print(result.status) # "completed" print(result.result) ``` -------------------------------- ### Start Non-blocking Extraction Job Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Starts an extraction job without waiting for completion. Use this for background processing and retrieve results later using the job ID. ```python job = client.extract.start( StartExtractJobParams(urls=["https://example.com"], prompt="Get all contact emails.") ) import time while True: s = client.extract.get_status(job.job_id) if s.status in ("completed", "failed"): break time.sleep(2) final = client.extract.get(job.job_id) print(final.data) ``` -------------------------------- ### Manage Browser Profiles with Hyperbrowser SDK Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Demonstrates creating, listing, getting, using, and deleting persistent browser profiles. Profiles preserve cookies, localStorage, and browsing state across sessions. Ensure `persist_changes=True` to save modifications back to the profile. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateProfileParams, ProfileListParams, CreateSessionParams, CreateSessionProfile client = Hyperbrowser(api_key="your-api-key") # Create a named profile profile = client.profiles.create(CreateProfileParams(name="my-logged-in-profile")) print(profile.id) # "pro_abc123" # List all profiles result = client.profiles.list(ProfileListParams(page=1, limit=20)) for p in result.profiles: print(p.id, p.name) # Get a specific profile p = client.profiles.get(profile.id) print(p.id, p.created_at) # Use the profile in a session (with persistence) session = client.sessions.create( CreateSessionParams( profile=CreateSessionProfile( id=profile.id, persist_changes=True, # save changes back to profile persist_network_cache=False, ) ) ) print(session.ws_endpoint) client.sessions.stop(session.id) # Delete a profile client.profiles.delete(profile.id) ``` -------------------------------- ### Start and Wait for Full Site Crawl Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates a blocking crawl job for a given URL, specifying maximum pages, scrape options, and whether to follow links or ignore the sitemap. Retrieves results upon completion. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartCrawlJobParams, ScrapeOptions client = Hyperbrowser(api_key="your-api-key") # Start and wait for a full site crawl result = client.crawl.start_and_wait( StartCrawlJobParams( url="https://docs.example.com", max_pages=50, scrape_options=ScrapeOptions(formats=["markdown"], only_main_content=True), follow_links=True, ignore_sitemap=False, ) ) print(result.status) # "completed" print(result.total_crawled_pages) # e.g. 42 for page in result.data: print(page.url, len(page.markdown or ""), "chars") ``` -------------------------------- ### Start Web Crawl Job with Markdown and JSON Output Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates a web crawl job for a given URL, specifying maximum pages to crawl and configuring output formats to include both Markdown and structured JSON based on a Pydantic schema. The job runs and waits for completion. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import ( StartWebCrawlJobParams, FetchOutputFormats, FetchOutputMarkdown, FetchOutputJson, ) from pydantic import BaseModel from typing import Optional client = Hyperbrowser(api_key="your-api-key") class ArticleMeta(BaseModel): title: str author: Optional[str] published_date: Optional[str] # Crawl with markdown + structured JSON output result = client.web.crawl.start_and_wait( StartWebCrawlJobParams( url="https://blog.example.com", max_pages=20, outputs=FetchOutputFormats( formats=[ FetchOutputMarkdown(), FetchOutputJson(schema_=ArticleMeta), ] ), ) ) print(result.status) print(result.total_pages) for page in result.data: print(page.url) print(page.markdown[:200] if page.markdown else "") print(page.json_data) ``` -------------------------------- ### Start and Wait for Single-Page Scrape Job Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initiates a scrape job for a single URL, specifying formats, options for main content extraction, waiting time, screenshot settings, and stealth mode for the session. This is a blocking call. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import ( StartScrapeJobParams, StartBatchScrapeJobParams, ScrapeOptions, ScreenshotOptions, CreateSessionParams, ) client = Hyperbrowser(api_key="your-api-key") # Single-page scrape (blocking) result = client.scrape.start_and_wait( StartScrapeJobParams( url="https://news.ycombinator.com/", scrape_options=ScrapeOptions( formats=["markdown", "html", "links", "screenshot"], only_main_content=True, wait_for=1000, screenshot_options=ScreenshotOptions(full_page=True, format="png"), ), session_options=CreateSessionParams(use_stealth=True), ) ) print(result.status) # "completed" print(result.data.markdown) # markdown content print(result.data.links[:5]) # list of URLs ``` -------------------------------- ### Client Initialization Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initialize sync and async clients with an API key, either via constructor argument or environment variable. Custom base URLs and runtime proxies are also supported. ```APIDOC ## Client Initialization Initializing sync and async clients with API key via constructor or environment variable. ```python import os from hyperbrowser import Hyperbrowser, AsyncHyperbrowser # Via constructor argument client = Hyperbrowser(api_key="your-api-key") # Via environment variable HYPERBROWSER_API_KEY os.environ["HYPERBROWSER_API_KEY"] = "your-api-key" client = Hyperbrowser() # Custom base URL and runtime proxy client = Hyperbrowser( api_key="your-api-key", base_url="https://api.hyperbrowser.ai", # default runtime_proxy_override="http://proxy:8080", ) # Async client (identical interface) async_client = AsyncHyperbrowser(api_key="your-api-key") # Sync client used as context manager (auto-close) with Hyperbrowser(api_key="your-api-key") as client: session = client.sessions.create() print(session.id, session.ws_endpoint) client.sessions.stop(session.id) ``` ``` -------------------------------- ### Manage Volumes and Mount Them in a Sandbox Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md Create a persistent volume, list all volumes, retrieve a specific volume, and then create a sandbox that mounts this volume. This allows for data persistence across sandbox instances. The `type` can be `rw` or `ro`. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateSandboxParams, CreateVolumeParams, SandboxVolumeMount client = Hyperbrowser(api_key="test-key") volume = client.volumes.create(CreateVolumeParams(name="project-cache")) all_volumes = client.volumes.list() same_volume = client.volumes.get(volume.id) sandbox = client.sandboxes.create( CreateSandboxParams( image_name="node", mounts={ "/workspace/cache": SandboxVolumeMount( id=same_volume.id, type="rw", shared=True, ) }, ) ) sandbox.stop() client.close() ``` -------------------------------- ### Initialize Hyperbrowser Clients Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Initialize synchronous and asynchronous clients using an API key. The API key can be provided via the constructor or the HYPERBROWSER_API_KEY environment variable. Custom base URLs and runtime proxies can also be configured. The sync client can be used as a context manager for automatic resource cleanup. ```python import os from hyperbrowser import Hyperbrowser, AsyncHyperbrowser # Via constructor argument client = Hyperbrowser(api_key="your-api-key") # Via environment variable HYPERBROWSER_API_KEY os.environ["HYPERBROWSER_API_KEY"] = "your-api-key" client = Hyperbrowser() # Custom base URL and runtime proxy client = Hyperbrowser( api_key="your-api-key", base_url="https://api.hyperbrowser.ai", # default runtime_proxy_override="http://proxy:8080", ) # Async client (identical interface) async_client = AsyncHyperbrowser(api_key="your-api-key") # Sync client used as context manager (auto-close) with Hyperbrowser(api_key="your-api-key") as client: session = client.sessions.create() print(session.id, session.ws_endpoint) client.sessions.stop(session.id) ``` -------------------------------- ### Create Sandbox with Pre-exposed Ports Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md Create a sandbox environment using a specified Docker image and expose specific ports with authentication enabled. This is useful for running applications that need network access. The `browser_url` for the first exposed port is printed. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateSandboxParams, SandboxExposeParams client = Hyperbrowser(api_key="test-key") sandbox = client.sandboxes.create( CreateSandboxParams( image_name="node", cpu=4, memory_mib=4096, disk_mib=8192, exposed_ports=[SandboxExposeParams(port=3000, auth=True)], ) ) print(sandbox.exposed_ports[0].browser_url) print(sandbox.cpu, sandbox.memory_mib, sandbox.disk_mib) sandbox.stop() client.close() ``` -------------------------------- ### Create and Manage Sandboxes with Hyperbrowser SDK Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Details the creation and management of isolated sandbox environments. This includes configuring resources (CPU, memory, disk), exposing ports, executing commands, performing file operations, managing terminals, and creating snapshots. Use `SandboxExecParams` for detailed command execution options. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import ( CreateSandboxParams, SandboxExposeParams, SandboxListParams, SandboxSnapshotListParams, SandboxMemorySnapshotParams, StartSandboxFromSnapshotParams, SandboxFileWriteEntry, SandboxTerminalCreateParams, SandboxExecParams, ) client = Hyperbrowser(api_key="your-api-key") # Create a sandbox with custom resources and exposed ports sandbox = client.sandboxes.create( CreateSandboxParams( image_name="node", cpu=4, memory_mib=4096, disk_mib=8192, exposed_ports=[SandboxExposeParams(port=3000, auth=True)], ) ) print(sandbox.id) print(sandbox.exposed_ports[0].browser_url) # authenticated browser-accessible URL # Execute a command result = sandbox.exec("node --version") print(result.stdout, result.exit_code) # Execute with full options result2 = sandbox.exec( SandboxExecParams( cmd=["npm", "install"], cwd="/workspace", env={"NODE_ENV": "production"}, timeout_ms=30000, ) ) # File operations: batch write sandbox.files.write([ SandboxFileWriteEntry(path="/tmp/config.json", data='{"debug":true}', mode="600"), SandboxFileWriteEntry(path="/tmp/data.bin", data=b"\x00\x01\x02"), ]) # Read a file content = sandbox.files.read("/tmp/config.json") print(content) # '{"debug":true}' # Terminal: create a persistent interactive terminal terminal = sandbox.terminal.create(SandboxTerminalCreateParams(command="bash")) connection = terminal.attach(cursor=0) connection.send_input("echo hello\n") for event in connection.events(): print(event) break # Expose/unexpose ports dynamically expose_result = sandbox.expose(SandboxExposeParams(port=8080, auth=False)) print(expose_result.url, expose_result.browser_url) sandbox.unexpose(8080) # Create a memory snapshot for fast resume snapshot = sandbox.create_memory_snapshot(SandboxMemorySnapshotParams(name="after-install")) print(snapshot.id) # List sandboxes with filters sandboxes = client.sandboxes.list( SandboxListParams(status="active", search="node", limit=10) ) for s in sandboxes.sandboxes: print(s.id, s.status) ``` -------------------------------- ### Batch File Writes with Per-File Options Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md Shows how to write multiple files to a sandbox in a single batch operation, with options like append mode and file permissions configurable per file. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateSandboxParams, SandboxFileWriteEntry client = Hyperbrowser(api_key="test-key") sandbox = client.sandboxes.create(CreateSandboxParams(image_name="node")) sandbox.files.write( [ SandboxFileWriteEntry( path="/tmp/config.json", data='{"debug":true}\n', append=True, mode="600", ), SandboxFileWriteEntry( path="/tmp/blob.bin", data=b"\x00\x01\x02", ), ] ) ``` -------------------------------- ### Expose and Unexpose Sandbox Ports Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md Demonstrates how to expose a port for external access and then unexpose it. Ensure the sandbox is created before attempting to expose ports. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateSandboxParams, SandboxExposeParams client = Hyperbrowser(api_key="test-key") sandbox = client.sandboxes.create( CreateSandboxParams( image_name="node", cpu=2, memory_mib=2048, disk_mib=8192 ) ) result = sandbox.expose(SandboxExposeParams(port=8080, auth=True)) print(result.url, result.browser_url) sandbox.unexpose(8080) ``` -------------------------------- ### List Available Sandbox Images Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Lists all available sandbox images and prints their names. Requires an initialized Hyperbrowser client. ```python images = client.sandboxes.list_images() for img in images.images: print(img.name) ``` -------------------------------- ### Create and Manage Volumes Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Demonstrates creating a named persistent volume, listing all available volumes, and retrieving a specific volume by its ID. Volumes can be used for shared or durable storage. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateVolumeParams, CreateSandboxParams, SandboxVolumeMount client = Hyperbrowser(api_key="your-api-key") # Create a named volume volume = client.volumes.create(CreateVolumeParams(name="project-cache")) print(volume.id) # "vol_abc123" print(volume.name) # "project-cache" # List all volumes all_volumes = client.volumes.list() for v in all_volumes.volumes: print(v.id, v.name) # Get a specific volume v = client.volumes.get(volume.id) ``` -------------------------------- ### Format Code with Ruff Source: https://github.com/hyperbrowserai/python-sdk/blob/main/CLAUDE.md Formats the codebase according to defined style guidelines using Ruff. Run this before committing code. ```bash poetry run ruff format . ``` -------------------------------- ### Connect to Existing Sandbox Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Establishes a connection to an already running sandbox using its unique identifier. Prints the current status of the connected sandbox. ```python existing = client.sandboxes.connect("snd_existing123") print(existing.status) ``` -------------------------------- ### List Sandboxes with Filters Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md List sandboxes with applied filters for status, search terms, and time ranges. This helps in managing and retrieving specific sandbox instances based on various criteria. The `limit` parameter controls the number of results returned. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import SandboxListParams client = Hyperbrowser(api_key="test-key") result = client.sandboxes.list( SandboxListParams( status="active", search="sandbox", start=1711929600000, end=1712016000000, limit=20, ) ) for sandbox in result.sandboxes: print(sandbox.id, sandbox.status) ``` -------------------------------- ### Manage Cloud Browser Sessions Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Create, inspect, and manage cloud browser sessions with various configuration options. This includes setting stealth mode, proxies, profiles, recording, CAPTCHA solving, and more. Sessions can be extended, proxies updated at runtime, and profile persistence configured. Recordings, logs, and uploaded files can be accessed. Sessions can be stopped when no longer needed. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateSessionParams, SessionListParams, UpdateSessionProfileParams, UpdateSessionProxyParams client = Hyperbrowser(api_key="your-api-key") # Create a fully configured session session = client.sessions.create( CreateSessionParams( use_stealth=True, use_proxy=True, proxy_country="US", solve_captchas=True, adblock=True, enable_web_recording=True, enable_video_web_recording=True, enable_log_capture=True, timeout_minutes=10, locales=["en"], ) ) print(session.id) # "ses_abc123" print(session.ws_endpoint) # "wss://..." print(session.live_url) # live view URL # Get session details with a fresh live view TTL detail = client.sessions.get(session.id) # List sessions with pagination result = client.sessions.list(SessionListParams(status="active", page=1, limit=20)) print(result.total_count, result.has_more) for s in result.sessions: print(s.id, s.status, s.duration) # Extend session duration client.sessions.extend_session(session.id, duration_minutes=5) # Update proxy at runtime client.sessions.update_proxy_params( session.id, UpdateSessionProxyParams(enabled=True, location={"country": "GB"}), ) # Update profile persistence client.sessions.update_profile_params( session.id, UpdateSessionProfileParams(persist_changes=True, persist_network_cache=False), ) # Get session recordings recording_url = client.sessions.get_recording_url(session.id) video_url = client.sessions.get_video_recording_url(session.id) downloads_url = client.sessions.get_downloads_url(session.id) recordings = client.sessions.get_recording(session.id) # raw rrweb events # Upload a local file into the session upload = client.sessions.upload_file(session.id, "/path/to/file.pdf") print(upload.file_path) # List session event logs from hyperbrowser.models import SessionEventLogListParams logs = client.sessions.event_logs.list( session.id, SessionEventLogListParams(limit=50, types=["network_request"]), ) for log in logs.data: print(log.type, log.page_url, log.timestamp) # Stop session client.sessions.stop(session.id) ``` -------------------------------- ### Async Browser Automation with Pyppeteer Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Utilizes Pyppeteer in an asynchronous context to connect to a Hyperbrowser session, navigate a web page, and retrieve its title. ```python import asyncio from pyppeteer import connect from hyperbrowser import AsyncHyperbrowser async def main(): async with AsyncHyperbrowser(api_key="your-api-key") as client: session = await client.sessions.create() browser = await connect(browserWSEndpoint=session.ws_endpoint, defaultViewport=None) pages = await browser.pages() page = pages[0] await page.goto("https://news.ycombinator.com/") print(await page.title()) await browser.disconnect() await client.sessions.stop(session.id) asyncio.run(main()) ``` -------------------------------- ### List Snapshots for an Image Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Retrieves a list of snapshots for a specified image, filtering by creation status and limiting the results. Ensure the 'node' image and 'created' status are valid for your environment. ```python snapshots = client.sandboxes.list_snapshots( SandboxSnapshotListParams(image_name="node", status="created", limit=5) ) ``` -------------------------------- ### Upload and Use Custom Chrome Extensions Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Shows how to upload a packed Chrome extension (.crx file) and use it within a browser session. The extension ID is returned upon successful upload. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateExtensionParams, CreateSessionParams client = Hyperbrowser(api_key="your-api-key") # Upload a packed .crx extension ext = client.extensions.create( CreateExtensionParams(file_path="/path/to/my-extension.crx") ) print(ext.id) # "ext_abc123" print(ext.name) # extension display name # List all uploaded extensions extensions = client.extensions.list() for e in extensions: print(e.id, e.name) # Use an extension in a session session = client.sessions.create( CreateSessionParams(extension_ids=[ext.id]) ) print(session.ws_endpoint) client.sessions.stop(session.id) ``` -------------------------------- ### List Snapshots for a Specific Image Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md Retrieve a list of snapshots for a given Docker image, filtered by status and a specified limit. This is useful for managing image versions and rollbacks. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import SandboxSnapshotListParams client = Hyperbrowser(api_key="test-key") snapshots = client.sandboxes.list_snapshots( SandboxSnapshotListParams(image_name="node", status="created", limit=10) ) ``` -------------------------------- ### Async HyperAgent Task Execution Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Demonstrates how to run a HyperAgent task asynchronously using `AsyncHyperbrowser`. This is suitable for non-blocking operations within an asyncio event loop. ```python import asyncio from hyperbrowser import AsyncHyperbrowser async def run_agent(): async with AsyncHyperbrowser(api_key="your-api-key") as client: result = await client.agents.hyper_agent.start_and_wait( StartHyperAgentTaskParams(task="What is the current Bitcoin price on coinmarketcap.com?") ) print(result.result) asyncio.run(run_agent()) ``` -------------------------------- ### OpenAI AI Tool Integration Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Integrates Hyperbrowser tools with OpenAI's chat completions API. Requires OpenAI client and Hyperbrowser client initialization. Handles tool calls for web scraping. ```python import json import openai from hyperbrowser import Hyperbrowser from hyperbrowser.tools.openai import ( SCRAPE_TOOL_OPENAI, CRAWL_TOOL_OPENAI, EXTRACT_TOOL_OPENAI, SCREENSHOT_TOOL_OPENAI, BROWSER_USE_TOOL_OPENAI, ) from hyperbrowser.models import StartScrapeJobParams, ScrapeOptions hb_client = Hyperbrowser(api_key="your-api-key") openai_client = openai.OpenAI() def handle_tool(name: str, args: dict) -> str: if name == "scrape_webpage": result = hb_client.scrape.start_and_wait( StartScrapeJobParams(url=args["url"], scrape_options=ScrapeOptions(formats=["markdown"])) ) return result.data.markdown or "" return "{}" messages = [{"role": "user", "content": "What are the main features listed on https://hyperbrowser.ai?"}] response = openai_client.chat.completions.create( model="gpt-4o", tools=[SCRAPE_TOOL_OPENAI, CRAWL_TOOL_OPENAI, EXTRACT_TOOL_OPENAI], messages=messages, ) while response.choices[0].finish_reason == "tool_calls": tool_call = response.choices[0].message.tool_calls[0] args = json.loads(tool_call.function.arguments) result = handle_tool(tool_call.function.name, args) messages += [ response.choices[0].message, {"role": "tool", "tool_call_id": tool_call.id, "content": result}, ] response = openai_client.chat.completions.create( model="gpt-4o", tools=[SCRAPE_TOOL_OPENAI, CRAWL_TOOL_OPENAI, EXTRACT_TOOL_OPENAI], messages=messages, ) print(response.choices[0].message.content) ``` -------------------------------- ### Sessions Management Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Manage cloud browser sessions, including creation with detailed configurations, inspection, listing, extending duration, updating runtime parameters, retrieving recordings, uploading files, and accessing event logs. ```APIDOC ## Sessions — `client.sessions` Creating, inspecting, and managing cloud browser sessions with full configuration options including stealth mode, proxies, profiles, recording, and CAPTCHA solving. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateSessionParams, SessionListParams, UpdateSessionProfileParams, UpdateSessionProxyParams client = Hyperbrowser(api_key="your-api-key") # Create a fully configured session session = client.sessions.create( CreateSessionParams( use_stealth=True, use_proxy=True, proxy_country="US", solve_captchas=True, adblock=True, enable_web_recording=True, enable_video_web_recording=True, enable_log_capture=True, timeout_minutes=10, locales=["en"], ) ) print(session.id) # "ses_abc123" print(session.ws_endpoint) # "wss://..." print(session.live_url) # live view URL # Get session details with a fresh live view TTL detail = client.sessions.get(session.id) # List sessions with pagination result = client.sessions.list(SessionListParams(status="active", page=1, limit=20)) print(result.total_count, result.has_more) for s in result.sessions: print(s.id, s.status, s.duration) # Extend session duration client.sessions.extend_session(session.id, duration_minutes=5) # Update proxy at runtime client.sessions.update_proxy_params( session.id, UpdateSessionProxyParams(enabled=True, location={"country": "GB"}), ) # Update profile persistence client.sessions.update_profile_params( session.id, UpdateSessionProfileParams(persist_changes=True, persist_network_cache=False), ) # Get session recordings recording_url = client.sessions.get_recording_url(session.id) video_url = client.sessions.get_video_recording_url(session.id) downloads_url = client.sessions.get_downloads_url(session.id) recordings = client.sessions.get_recording(session.id) # raw rrweb events # Upload a local file into the session upload = client.sessions.upload_file(session.id, "/path/to/file.pdf") print(upload.file_path) # List session event logs from hyperbrowser.models import SessionEventLogListParams logs = client.sessions.event_logs.list( session.id, SessionEventLogListParams(limit=50, types=["network_request"]), ) for log in logs.data: print(log.type, log.page_url, log.timestamp) # Stop session client.sessions.stop(session.id) ``` ``` -------------------------------- ### Async Browser Session Usage Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md Create and manage an asynchronous browser session. This snippet demonstrates connecting to a remote browser, navigating to a website, and retrieving the page title. Ensure the `HYPERBROWSER_API_KEY` is set. ```python import asyncio from pyppeteer import connect from hyperbrowser import AsyncHyperbrowser HYPERBROWSER_API_KEY = "test-key" async def main(): async with AsyncHyperbrowser(api_key=HYPERBROWSER_API_KEY) as client: session = await client.sessions.create() ws_endpoint = session.ws_endpoint browser = await connect(browserWSEndpoint=ws_endpoint, defaultViewport=None) # Get pages pages = await browser.pages() if not pages: raise Exception("No pages available") page = pages[0] # Navigate to a website print("Navigating to Hacker News...") await page.goto("https://news.ycombinator.com/") page_title = await page.title() print("Page title:", page_title) await page.close() await browser.disconnect() await client.sessions.stop(session.id) print("Session completed!") # Run the asyncio event loop asyncio.get_event_loop().run_until_complete(main()) ``` -------------------------------- ### Resume Terminal Output After Reconnect Source: https://github.com/hyperbrowserai/python-sdk/blob/main/README.md Illustrates how to attach to a sandbox terminal and stream its output, allowing for resuming output after a connection is re-established. The cursor parameter can be used to specify where to resume. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateSandboxParams, SandboxTerminalCreateParams client = Hyperbrowser(api_key="test-key") sandbox = client.sandboxes.create(CreateSandboxParams(image_name="node")) terminal = sandbox.terminal.create(SandboxTerminalCreateParams(command="bash")) connection = terminal.attach(cursor=10) for event in connection.events(): print(event) ``` -------------------------------- ### Sandboxes Management Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Create and manage isolated cloud sandbox environments with configurable resources, filesystem access, terminal emulation, and port exposure. Sandboxes provide isolated environments for running code and applications. ```APIDOC ## Sandboxes — `client.sandboxes` Creating and managing isolated cloud sandbox environments with configurable compute resources, filesystem access, terminal emulation, and port exposure. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import ( CreateSandboxParams, SandboxExposeParams, SandboxListParams, SandboxSnapshotListParams, SandboxMemorySnapshotParams, StartSandboxFromSnapshotParams, SandboxFileWriteEntry, SandboxTerminalCreateParams, SandboxExecParams, ) client = Hyperbrowser(api_key="your-api-key") # Create a sandbox with custom resources and exposed ports sandbox = client.sandboxes.create( CreateSandboxParams( image_name="node", cpu=4, memory_mib=4096, disk_mib=8192, exposed_ports=[SandboxExposeParams(port=3000, auth=True)], ) ) print(sandbox.id) print(sandbox.exposed_ports[0].browser_url) # authenticated browser-accessible URL # Execute a command result = sandbox.exec("node --version") print(result.stdout, result.exit_code) # Execute with full options result2 = sandbox.exec( SandboxExecParams( cmd=["npm", "install"], cwd="/workspace", env={"NODE_ENV": "production"}, timeout_ms=30000, ) ) # File operations: batch write sandbox.files.write([ SandboxFileWriteEntry(path="/tmp/config.json", data='{"debug":true}', mode="600"), SandboxFileWriteEntry(path="/tmp/data.bin", data=b"\x00\x01\x02"), ]) # Read a file content = sandbox.files.read("/tmp/config.json") print(content) # '{"debug":true}' # Terminal: create a persistent interactive terminal terminal = sandbox.terminal.create(SandboxTerminalCreateParams(command="bash")) connection = terminal.attach(cursor=0) connection.send_input("echo hello\n") for event in connection.events(): print(event) break # Expose/unexpose ports dynamically expose_result = sandbox.expose(SandboxExposeParams(port=8080, auth=False)) print(expose_result.url, expose_result.browser_url) sandbox.unexpose(8080) # Create a memory snapshot for fast resume snapshot = sandbox.create_memory_snapshot(SandboxMemorySnapshotParams(name="after-install")) print(snapshot.id) # List sandboxes with filters sandboxes = client.sandboxes.list( SandboxListParams(status="active", search="node", limit=10) ) for s in sandboxes.sandboxes: print(s.id, s.status) ``` ``` -------------------------------- ### Run Linting with Ruff Source: https://github.com/hyperbrowserai/python-sdk/blob/main/CLAUDE.md Checks code for style and potential errors using Ruff. This command should be run regularly to maintain code quality. ```bash poetry run ruff check . ``` -------------------------------- ### Web Batch Fetch Job Source: https://context7.com/hyperbrowserai/python-sdk/llms.txt Perform batch fetching of multiple URLs in parallel with configurable output formats like markdown and screenshots. ```APIDOC ## Web Batch Fetch — `client.web.batch_fetch` Fetching and processing multiple URLs in parallel with configurable output formats including markdown, screenshots, and structured data. ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import ( StartBatchFetchJobParams, FetchOutputFormats, FetchOutputMarkdown, FetchOutputScreenshot, ) client = Hyperbrowser(api_key="your-api-key") result = client.web.batch_fetch.start_and_wait( StartBatchFetchJobParams( urls=[ "https://example.com", "https://example.org", "https://python.org", ], outputs=FetchOutputFormats( formats=[FetchOutputMarkdown(), FetchOutputScreenshot()] ), ) ) print(result.status) print(result.total_pages) for page in result.data: print(page.url, page.status) if page.markdown: print(page.markdown[:300]) if page.screenshot: print(f"Screenshot (base64 len): {len(page.screenshot)}") ``` ```