Skip to content

add restaurant and airline examples #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
90 changes: 90 additions & 0 deletions examples/airline_prices/api_aeromexico.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
from playwright.sync_api import sync_playwright, Playwright
import os
import time
import requests
from dotenv import load_dotenv
load_dotenv()

def create_session():
url = "https://www.browserbase.com/v1/sessions"

payload = {
"projectId": os.environ["BROWSERBASE_PROJECT_ID"],
"keepAlive": False,
"proxies": True,
}
headers = {
"X-BB-API-Key": os.environ["BROWSERBASE_API_KEY"],
"Content-Type": "application/json"
}

response = requests.request("POST", url, json=payload, headers=headers)

return response.json()

def create_debug_url(session_id):
url = f"https://www.browserbase.com/v1/sessions/{session_id}/debug"

headers = {"X-BB-API-Key": os.environ["BROWSERBASE_API_KEY"]}

response = requests.request("GET", url, headers=headers)
debug_url = response.json()['debuggerFullscreenUrl']

print(debug_url)

def main():
# Create session
session = create_session()
session_id = session["id"]
print(f"Session ID: {session_id}")

create_debug_url(session_id)

# Use Playwright to interact with the session
with sync_playwright() as playwright:
browser = playwright.chromium.connect_over_cdp(
f'wss://connect.browserbase.com?apiKey={os.environ["BROWSERBASE_API_KEY"]}&sessionId={session_id}'
)

# Get the first page or create a new one
context = browser.contexts[0]
page = context.pages[0] if context.pages else context.new_page()

# Navigate to the website
page.goto("https://www.aeromexico.com/en-us")

# Handle cookies modal
page.wait_for_selector('.CookiesModal--btn.Btn.Btn--filledRed', state='visible', timeout=60000)
page.locator('button', has_text='Accept').click()
page.wait_for_selector('.Modal.Modal--HOME_COOKIES', state='hidden')

# Fill out origin and destination fields
page.get_by_placeholder("Type an origin").click()
page.get_by_placeholder("Type an origin").fill("SFO")
page.wait_for_selector(".NewBookerAirportAutocompleteList")
page.locator(".NewBookerAirportAutocompleteList").first.click()

page.get_by_placeholder("Please type a destination.").click()
page.get_by_placeholder("Please type a destination.").fill("MEX")
page.wait_for_selector(".NewBookerAirportAutocompleteList")
page.locator(".NewBookerAirportAutocompleteList").first.click()

# Select dates
page.get_by_text("Departure — Return").click()
page.get_by_role("button", name="1", exact=True).nth(1).click() # 1st of next month
page.get_by_role("button", name="8", exact=True).nth(1).click() # 8th of next month

# Search for flights
page.get_by_label("Find flight").click()

# Wait for the page to be idle
page.wait_for_load_state("networkidle", timeout=60000)

# Log the page content
print(page.content())

if __name__ == "__main__":
try:
main()
except Exception as e:
print(f"Error: {e}")
85 changes: 85 additions & 0 deletions examples/airline_prices/playwright_aeromexico.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { chromium } from "playwright-core";
import Browserbase from "@browserbasehq/sdk";
import { config } from "dotenv";
config();

console.info("Launching browser...");

const BROWSERBASE_API_KEY = process.env.BROWSERBASE_API_KEY;
const BROWSERBASE_PROJECT_ID = process.env.BROWSERBASE_PROJECT_ID;

const bb = new Browserbase({
apiKey: BROWSERBASE_API_KEY,
});

(async () => {
// Create a new session
const session = await bb.sessions.create({
projectId: BROWSERBASE_PROJECT_ID,
keepAlive: true,
proxies: true,
browserSettings: {
context:
{
id: BROWSERBASE_CONTEXT_ID,
persist: true,
}
}
});

// Connect to the session
const browser = await chromium.connectOverCDP(session.connectUrl);

// Getting the default context to ensure the sessions are recorded.
const defaultContext = browser.contexts()[0];
const page = defaultContext?.pages()[0];
console.log(
`View sessionreplay at https://browserbase.com/sessions/${session.id}`,
);
const airline = await page.goto("https://www.aeromexico.com/en-us");

// Wait for cookie accept button to be visible
await page.waitForSelector('.CookiesModal--btn.Btn.Btn--filledRed', { state: 'visible', timeout: 60000})
// Click the accept button
await page.locator('button').filter({ hasText: 'Accept' }).click();
// Wait for cookie modal to disappear
await page.waitForSelector('.Modal.Modal--HOME_COOKIES', { state: 'hidden' })

// Wait for the airport origin input field to appear
await page.getByPlaceholder('Type an origin').click()
await page.getByPlaceholder('Type an origin').fill('SFO');

// // Wait for suggestions list to appear and select first matching option
await page.waitForSelector('.NewBookerAirportAutocompleteList')
await page.locator('.NewBookerAirportAutocompleteList').first().click()

await page.getByPlaceholder('Please type a destination.').click();
await page.getByPlaceholder('Please type a destination.').fill('MEX');

// Wait for suggestions list to appear and select first matching option
await page.waitForSelector('.NewBookerAirportAutocompleteList')
await page.locator('.NewBookerAirportAutocompleteList').first().click()

await page.getByText('Departure — Return').click();
await page.getByRole('button', { name: '1', exact: true }).nth(1).click();
await page.getByRole('button', { name: '8', exact: true }).nth(1).click();

await page.getByLabel('Find flight').click();

// wait for 20 seconds
await new Promise(resolve => setTimeout(resolve, 20000));

// console log the page source
// console.log("Waiting for FlightOptionsList-flightOption to be visible...");
// await page.waitForSelector('.FlightOptionsList-flightOption', {
// state: 'visible', // Ensure the element is visible (default is 'attached')
// });
// console.log('FlightOptionsList-flightOption is now visible!');

// console log the page source with pretty print
console.log(JSON.stringify(await page.content(), null, 2));
// console.log(await page.content());

await page.close();
await browser.close();
})().catch((error) => console.error(error.message));
77 changes: 77 additions & 0 deletions examples/airline_prices/sdk_aeromexico.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import os
import time
from playwright.sync_api import sync_playwright
from browserbase import Browserbase
# import environment variables
from dotenv import load_dotenv
load_dotenv()

# Load environment variables
BROWSERBASE_API_KEY = os.getenv("BROWSERBASE_API_KEY")
BROWSERBASE_PROJECT_ID = os.getenv("BROWSERBASE_PROJECT_ID")

# Initialize Browserbase SDK
bb = Browserbase(api_key=BROWSERBASE_API_KEY)

print("Launching browser...")

def main():
with sync_playwright() as p:
# Create a new session
session = bb.sessions.create(
project_id=BROWSERBASE_PROJECT_ID,
# keep_alive=True,
proxies=True
)

# Connect to the session using CDP
browser = p.chromium.connect_over_cdp(session.connect_url)

# Get the default context and page
context = browser.contexts[0]
page = context.pages[0]

print(f"View session replay at https://browserbase.com/sessions/{session.id}")

# # Navigate to the website
page.goto("https://www.aeromexico.com/en-us")

# Handle cookies modal
page.wait_for_selector('.CookiesModal--btn.Btn.Btn--filledRed', state='visible', timeout=60000)
page.locator('button', has_text='Accept').click()
page.wait_for_selector('.Modal.Modal--HOME_COOKIES', state='hidden')

# Fill out the origin and destination fields
page.get_by_placeholder("Type an origin").click()
page.get_by_placeholder("Type an origin").fill("SFO")
page.wait_for_selector(".NewBookerAirportAutocompleteList")
page.locator(".NewBookerAirportAutocompleteList").first.click()

page.get_by_placeholder("Please type a destination.").click()
page.get_by_placeholder("Please type a destination.").fill("MEX")
page.wait_for_selector(".NewBookerAirportAutocompleteList")
page.locator(".NewBookerAirportAutocompleteList").first.click()

# Select dates
page.get_by_text("Departure — Return").click()
page.get_by_role("button", name="1", exact=True).nth(1).click() # 1st of next month
page.get_by_role("button", name="8", exact=True).nth(1).click() # 8th of next month

# Search for flights
page.get_by_label("Find flight").click()

# wait for the page to be idle
page.wait_for_load_state('networkidle', timeout=60000)

# Log the page content
print(page.content())

# Close the page and browser
page.close()
browser.close()

if __name__ == "__main__":
try:
main()
except Exception as e:
print(f"Error: {e}")
44 changes: 44 additions & 0 deletions examples/airline_prices/stagehand_southwest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { chromium } from "playwright-core";
import Browserbase from "@browserbasehq/sdk";
import { config } from "dotenv";
config();
import { Stagehand } from '@browserbasehq/stagehand';
import z from 'zod';

const stagehand = new Stagehand({
env: "LOCAL",
verbose: 1,
});

await stagehand.init();

// Set the origin and destination
const origin = "SFO";
const destination = "LAX";

await stagehand.page.goto("https://www.southwest.com/");
await stagehand.act({ action: "select the round trip option" });
await stagehand.act({ action: `type in origin: ${origin}` });
await stagehand.act({ action: `select ${origin} from the origin options` });
await stagehand.act({ action: `type in destination: ${destination}` });
await stagehand.act({ action: `select ${destination} from the destination options` });
await stagehand.act({ action: "click the departure date of the first of next month" });
await stagehand.act({ action: "click the return date of the eighth of the month" });
await stagehand.act({ action: "click search for flights" });
await stagehand.act({ action: "select only the non stop flights" });

// Use stagehand to extract the flight data from the page
const flightData = await stagehand.extract({
instruction: "extract all of the flight data from the page, only include the flight number, departure and arrival times, and the price",
schema: z.object({
flights: z.object({
flightNumber: z.string(),
departureTime: z.string(),
arrivalTime: z.string(),
price: z.string(),
}).array(),
}),
domSettleTimeoutMs: 60_000
});

console.log(flightData);
30 changes: 30 additions & 0 deletions examples/restaurant_menu/stagehand_extract_menu_items.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import 'dotenv/config';
import { Stagehand } from '@browserbasehq/stagehand';
import z from 'zod';

const stagehand = new Stagehand({
env: "BROWSERBASE",
verbose: 1,
});

await stagehand.init();

const search_query = "ti piacera"

await stagehand.page.goto("https://www.google.com/");
await stagehand.act({ action: `type in search query: ${search_query} restaurant` });
await stagehand.act({ action: "click search" });
await stagehand.act({ action: "click do not share location" });
await stagehand.act({ action: "click the first search result" });
await stagehand.act({action: "click the menu option in the navbar"})
await stagehand.act({ action: "click the dinner menu from the dropdown" });

const dinner_menu_meats = await stagehand.extract({
action: "extract the menu items that contain meat on the dinner menu, only include the name of the dish, catorize by red and white meats",
schema: z.object({
red_meat_dishes: z.array(z.string()),
white_meat_dishes: z.array(z.string()),
}),
});

console.log(dinner_menu_meats);