Skip to main content

Overview

You can run Tzafon Computer using Playwright. Install the required dependencies:
uv add tzafon pytest-playwright requests
Tzafon with Playwright example:
Python
import requests
from playwright.sync_api import Playwright, sync_playwright

BASE_URL = "https://api.tzafon.ai"
TOKEN = "sk_your_api_key_here"  # Replace with your API key

def create_computer() -> str:
    print("Creating computer...")
    headers = {
        "Authorization": f"Bearer {TOKEN}",
        "Content-Type": "application/json",
    }
    resp = requests.request(
        "POST",
        f"{BASE_URL}/computers",
        json={"kind": "browser"},
        headers=headers,
        timeout=180,
    )
    data = resp.json()
    print(f"Created computer id={data['id']}")
    return data["id"]


def run(playwright: Playwright, cdp_url: str, computer_id: str) -> None:
    print(f"connecting to cdp url: {cdp_url}")
    browser = playwright.chromium.connect_over_cdp(cdp_url)
    
    context = browser.contexts[0]
    page = context.pages[0]

    print("opening wikipedia page")
    page.evaluate("location.href = 'https://www.wikipedia.com'")

    print("waiting for wikipedia to load")
    page.wait_for_function("document.readyState === 'complete' || document.readyState === 'interactive'", timeout=60000)

    print("filling search box")
    page.get_by_role("searchbox", name="Search").click()
    page.get_by_role("searchbox", name="Search").fill("Ada Lovelace")

    print("clicking enter button")
    page.keyboard.press("Enter")

    print("waiting 1 second")
    page.wait_for_timeout(1000)

    page.screenshot(path=f"screenshot_{computer_id}.png", full_page=False)
    print(f"Saved screenshot_{computer_id}.png")

    context.close()
    browser.close()


if __name__ == "__main__":
    computer_id = create_computer()
    cdp_url = f"{BASE_URL}/computers/{computer_id}/cdp?token={TOKEN}"
    with sync_playwright() as p:
        run(p, cdp_url, computer_id)