block-quote On this pagechevron-down
copy Copy chevron-down
Interacting with Browser Tasks Once you've initiated a browser task in Browser Swarm , you can connect to it using your preferred automation framework to perform various actions such as navigation, form submissions, and data extraction.
π Connecting to a Browser Task
After creating a browser task, you'll receive a connectUrl which is used to establish a connection with the browser instance. Here's how to connect using different frameworks:
π Playwright
Copy import { chromium } from ' playwright-core ' ;
import { createSession } from ' browser-swarm-sdk ' ;
const session = await createSession ( { browser : ' chromium ' } ) ;
const browser = await chromium . connectOverCDP ( session . connectUrl ) ;
const page = await browser . newPage () ;
await page . goto ( ' https://example.com ' ) ;
Copy from playwright . sync_api import sync_playwright
from browser_swarm import create_session
session = create_session ( browser = ' chromium ' )
with sync_playwright () as p :
browser = p . chromium . connect_over_cdp ( session . connect_url )
page = browser . new_page ()
page . goto ( ' https://example.com ' )
Copy import puppeteer from ' puppeteer-core ' ;
import { createSession } from ' browser-swarm-sdk ' ;
const session = await createSession ( { browser : ' chromium ' } ) ;
const browser = await puppeteer . connect ( { browserWSEndpoint : session . connectUrl } ) ;
const page = await browser . newPage () ;
await page . goto ( ' https://example.com ' ) ; Connection Best Practices
Timely Connection : Connect to the browser task within 5 minutes of creation to prevent automatic termination.
Keep Alive : For longer sessions, enable the keepAlive option during session creation.
Default Context : Use the default browser context to ensure compatibility with features like stealth mode.
Controlling the Browser
Once connected, you can control the browser using your framework's API. Common actions include:
Navigation : page.goto('https://example.com')
Clicking Elements : page.click('#submit')
Typing Text : page.type('#username', 'myUser')
Extracting Content : page.content()
Live View and Session Monitoring
Browser Swarm provides real-time monitoring tools:
Session Inspector : View live browser interactions, network requests, console logs, and performance metrics. ->
Embedded View : Integrate a live browser view into your application for real-time observation and control. ->
Ending a Browser Task
To end a browser task:
Programmatically : Use your framework's method, e.g., browser.close() or session.close().
Automatically : Tasks will terminate after a specified timeout or upon disconnection, unless keepAlive is enabled.
Properly ending tasks ensures resource optimization and prevents unnecessary charges.
For more advanced features like file downloads , stealth mode , and proxy integration , refer to the respective sections in this documentation.
Last updated 9 months ago