Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
66813e3
Added sample script which uses connectovercdp
Nov 14, 2025
e317281
.
Nov 14, 2025
232838d
Add GetCdpUrl.py to retrieve WebSocket URL
Ishita-Jinturkar Nov 23, 2025
072daa6
Create .env.example for Playwright configuration
Ishita-Jinturkar Nov 23, 2025
bec9c07
Fetch and connect to CDP WebSocket URL
Ishita-Jinturkar Dec 8, 2025
04f534d
Delete samples/cdp-tests/GetCdpUrl.py
Ishita-Jinturkar Dec 8, 2025
3aff180
Add remote browser search functionality for Amazon
Ishita-Jinturkar Dec 8, 2025
0eac278
Removed data from .env.example
Ishita-Jinturkar Dec 10, 2025
726a902
Update to Azure OpenAI for product search
Ishita-Jinturkar Dec 10, 2025
c2cb840
Change console.log to console.debug and update URL
Ishita-Jinturkar Dec 10, 2025
85ebc94
Refactor connection script for Playwright service
Ishita-Jinturkar Jan 19, 2026
c703f12
Refactor Playwright service URL handling
Ishita-Jinturkar Jan 19, 2026
e628926
Refactor Browser-Use-Remote.py for clarity and dotenv
Ishita-Jinturkar Jan 19, 2026
86e0f35
Refactor connectOverCDPScript.js to Python
Ishita-Jinturkar Jan 19, 2026
0371157
Revise .env.example for Playwright and Azure OpenAI
Ishita-Jinturkar Jan 19, 2026
909d57d
Refactor Browser-Use-Remote.py for clarity and updates
Ishita-Jinturkar Jan 19, 2026
36a05ef
Add Playwright Service Python client implementation
Ishita-Jinturkar Jan 19, 2026
3236193
Add Playwright testing example with remote browser support
Ishita-Jinturkar Jan 19, 2026
9a00d32
Update script name in usage instructions
Ishita-Jinturkar Jan 19, 2026
3fc4bfe
Fix script name in usage instructions
Ishita-Jinturkar Jan 19, 2026
31e1b87
Add README for Python CDP samples
Ishita-Jinturkar Jan 19, 2026
c952c5a
Add requirements.txt for Python sample dependencies
Ishita-Jinturkar Jan 19, 2026
04622a0
Add headers to CDP connection in connectOverCDPScript
Ishita-Jinturkar Jan 19, 2026
4ec7294
Add User-Agent header to CDP connection
Ishita-Jinturkar Jan 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions samples/cdp-tests/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Microsoft Playwright Service - Environment Variables
# Copy this file to .env and fill in your values

# Playwright Service (Required for all samples)
PLAYWRIGHT_SERVICE_URL=
PLAYWRIGHT_SERVICE_ACCESS_TOKEN=

# Azure OpenAI (Required for browser_use_remote.py only)
AZURE_OPENAI_API_KEY=
AZURE_OPENAI_ENDPOINT=
AZURE_OPENAI_API_VERSION=
160 changes: 160 additions & 0 deletions samples/cdp-tests/Browser-Use-Remote.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
"""
Amazon Product Search with Browser-Use + Hosted LLM (Azure OpenAI)

This script lets you search Amazon for products using a remote Playwright browser
(Microsoft Playwright Cloud) and a hosted LLM (Azure OpenAI).

----------------------------------------
📌 Prerequisites
----------------------------------------
1️⃣ Python environment with the following packages installed:
pip install aiohttp pydantic browser-use python-dotenv

2️⃣ Hosted LLM Setup (Azure OpenAI)
- Create an Azure OpenAI resource in the Azure Portal.
- Deploy a model (e.g., gpt-35-turbo).
- Set the following environment variables:

export AZURE_OPENAI_API_KEY="your_api_key_here"
export AZURE_OPENAI_ENDPOINT="https://<your-resource-name>.openai.azure.com/"
export AZURE_OPENAI_API_VERSION="2023-07-01-preview"

3️⃣ Playwright Remote Browser Setup
- Sign up for Microsoft Playwright Cloud.
- Obtain your service URL and access token.
- Set the following environment variables:

export PLAYWRIGHT_SERVICE_URL="wss://<region>.api.playwright.microsoft.com/playwrightworkspaces/<workspaceId>/browsers"
export PLAYWRIGHT_SERVICE_ACCESS_TOKEN="your_access_token"

----------------------------------------
📌 How to Use
----------------------------------------
1️⃣ Run the script:
python Browser-Use-Remote.py

2️⃣ Enter product keywords when prompted.
(Default is "wireless mouse" if you press Enter.)

3️⃣ The script will connect to the remote browser and hosted LLM to perform
the search and print structured results in the terminal.
"""

import asyncio
import os
from pydantic import BaseModel
from dotenv import load_dotenv
from browser_use import Agent
from browser_use.llm import AzureChatOpenAI
from browser_use.browser.session import BrowserSession
from browser_use.browser.profile import BrowserProfile

# Load environment variables from .env file
load_dotenv()

# Import the shared module
from playwright_service_client import get_cdp_endpoint


# --- Azure OpenAI Setup ---
def get_llm():
"""Initialize the hosted Azure OpenAI LLM."""
return AzureChatOpenAI(
model_name="gpt-35-turbo",
openai_api_key=os.environ["AZURE_OPENAI_API_KEY"],
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
deployment_name="gpt-35-turbo",
max_tokens=3000,
api_version=os.environ["AZURE_OPENAI_API_VERSION"],
)


# --- Remote Playwright Browser ---
async def create_remote_browser_session() -> BrowserSession:
"""
Create a remote Playwright browser session.
Returns a BrowserSession configured for browser-use.
"""
cdp_url = await get_cdp_endpoint()
print(f"🔗 Connected to Playwright Service")

profile = BrowserProfile(cdp_url=cdp_url)
return BrowserSession(browser_profile=profile)


# --- Data Models ---
class Product(BaseModel):
name: str
price: str
rating: str | None = None
reviews: str | None = None
url: str


class ProductSearchResults(BaseModel):
items: list[Product] = []


# --- Amazon Search Function ---
async def search_amazon_remote(keywords: str = 'wireless mouse'):
"""Search Amazon using remote browser + hosted Azure OpenAI LLM"""
print(f"🎯 Searching Amazon for: {keywords}")
print("🔧 Using: Remote Playwright Browser + Azure OpenAI LLM")

browser_session = await create_remote_browser_session()
llm = get_llm()

agent = Agent(
task=f"""
Go to Amazon (https://www.amazon.com) and search for "{keywords}".
Collect the top 5 product results.
For each product, extract:
- Product name
- Price
- Rating (stars)
- Number of reviews
- Product page URL
Return structured output.
""",
llm=llm,
browser_session=browser_session,
output_model_schema=ProductSearchResults,
)

print("🎯 Starting Amazon search...")
result = await agent.run()
print("✅ Search completed successfully!")
return result


# --- Main ---
async def main():
print("🛒 Amazon Product Search with Browser-Use + Azure OpenAI")
print("=" * 50)

keywords = input('Enter product keywords (default "wireless mouse"): ').strip() or 'wireless mouse'

try:
result = await search_amazon_remote(keywords)

if result and result.structured_output:
products = result.structured_output
print(f'\n{"=" * 70}')
print(f'Amazon Search Results for "{keywords}"')
print(f'{"=" * 70}\n')
for i, item in enumerate(products.items, 1):
print(f'{i}. Name: {item.name}')
print(f' Price: {item.price}')
if item.rating: print(f' Rating: {item.rating}')
if item.reviews: print(f' Reviews: {item.reviews}')
print(f' URL: {item.url}')
print(f'{"-" * 70}')
else:
print("❌ No products found or search failed")

except Exception as e:
print(f"❌ Error: {e}")


if __name__ == '__main__':
asyncio.run(main())
81 changes: 81 additions & 0 deletions samples/cdp-tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Microsoft Playwright Service - Python CDP Samples

Python samples for connecting to Microsoft Playwright Service via CDP.

## 📁 Files

| File | Use Case | Description |
|------|----------|-------------|
| `playwright_service_client.py` | Core Module | Shared client for all samples |
| `test_runner.py` | **Testing** | Test runner with helpers |
| `connectOverCDPScript.py` | **Manual** | Simple connect_over_cdp example |
| `Browser-Use-Remote.py` | **AI Agent** | Browser-Use + Azure OpenAI |

## 🚀 Quick Start

```bash
# Install dependencies
pip install -r requirements.txt

# Copy .env.example to .env and fill in your values
cp .env.example .env

# Run samples
python connectOverCDPScript.py # Basic CDP connection
python test_runner.py # Run example tests
pytest test_runner.py -v # With pytest
python Browser-Use-Remote.py # AI agent (requires Azure OpenAI)
```

## 📖 Usage Examples

### Basic CDP Connection
```python
from playwright.async_api import async_playwright
from playwright_service_client import get_cdp_endpoint

cdp_url = await get_cdp_endpoint()
async with async_playwright() as p:
browser = await p.chromium.connect_over_cdp(cdp_url)
page = await browser.new_page()
await page.goto("https://example.com")
```

### Test Automation
```python
from test_runner import remote_page

async with remote_page() as page:
await page.goto("https://example.com")
assert await page.title() == "Example Domain"
```

### AI Agent
```python
from playwright_service_client import get_cdp_endpoint
from browser_use.browser.profile import BrowserProfile

cdp_url = await get_cdp_endpoint()
profile = BrowserProfile(cdp_url=cdp_url)
```

## 🔧 Environment Variables

Copy `.env.example` to `.env` and fill in your values:

```bash
PLAYWRIGHT_SERVICE_URL=wss://<region>.api.playwright.microsoft.com/playwrightworkspaces/<workspaceId>/browsers
PLAYWRIGHT_SERVICE_ACCESS_TOKEN=your_access_token

# For AI agent example only
AZURE_OPENAI_API_KEY=your_api_key
AZURE_OPENAI_ENDPOINT=https://<resource>.openai.azure.com/
AZURE_OPENAI_API_VERSION=2023-07-01-preview
```

## 📚 Resources

- [Microsoft Playwright Service](https://learn.microsoft.com/azure/playwright-testing/)
- [Playwright Python](https://playwright.dev/python/)
- [Browser-Use](https://github.com/browser-use/browser-use)

93 changes: 93 additions & 0 deletions samples/cdp-tests/connectOverCDPScript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""
Connect Over CDP - Microsoft Playwright Service

Simple example showing how to connect to a remote browser via CDP.
This demonstrates a NON-TESTING scenario for manual browser automation.

----------------------------------------
📌 Prerequisites
----------------------------------------
1️⃣ Python environment with the following packages installed:
pip install playwright aiohttp python-dotenv

2️⃣ Playwright Remote Browser Setup
- Sign up for Microsoft Playwright Service.
- Obtain your service URL and access token.
- Copy .env.example to .env and fill in your values:

PLAYWRIGHT_SERVICE_URL=wss://<region>.api.playwright.microsoft.com/playwrightworkspaces/<workspaceId>/browsers
PLAYWRIGHT_SERVICE_ACCESS_TOKEN=your_access_token

----------------------------------------
📌 How to Use
----------------------------------------
1️⃣ Run the script:
python connectOverCDPScript.py

2️⃣ The script will:
- Connect to the remote browser
- Navigate to example.com
- Take a screenshot
- Extract page content
- Click a link
"""

import asyncio
from playwright.async_api import async_playwright
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

from playwright_service_client import get_cdp_endpoint


async def main():
"""Connect to a remote browser via CDP and perform basic operations."""

print("🔗 Connecting to Microsoft Playwright Service...")

# Step 1: Get CDP endpoint from the service
cdp_url = await get_cdp_endpoint()
print(f"✅ Got CDP endpoint")

# Step 2: Connect to remote browser using Playwright
async with async_playwright() as p:
browser = await p.chromium.connect_over_cdp(
cdp_url,
headers={"User-Agent": "Chrome-DevTools-Protocol/1.3"}
)
print(f"✅ Connected to remote browser")

# Step 3: Use the browser
context = await browser.new_context()
page = await context.new_page()

# Example: Navigate and take screenshot
print("📄 Navigating to example.com...")
await page.goto("https://example.com")

title = await page.title()
print(f"📌 Page title: {title}")

# Take a screenshot
await page.screenshot(path="screenshot.png")
print("📸 Screenshot saved to screenshot.png")

# Example: Extract content
heading = await page.locator("h1").text_content()
print(f"📝 Page heading: {heading}")

# Example: Click a link
await page.click("a")
await page.wait_for_load_state("networkidle")
print(f"🔗 Navigated to: {page.url}")

# Cleanup
await context.close()
await browser.close()
print("✅ Done!")


if __name__ == "__main__":
asyncio.run(main())
Loading