Skip to content

Commit 50b9017

Browse files
authored
Merge pull request #26 from browserbase/anirudh/e2e-selenium
Add examples in Selenium
2 parents 8e213aa + 6eedef2 commit 50b9017

12 files changed

+112
-82
lines changed

examples/__init__.py

-3
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,6 @@
88
load_dotenv(override=True)
99

1010
# Make sure we have the required environment variables
11-
BROWSERBASE_CONNECT_URL = os.environ.get(
12-
"BROWSERBASE_CONNECT_URL", "wss://connect.browserbase.com"
13-
)
1411
_BROWSERBASE_API_KEY = os.environ.get("BROWSERBASE_API_KEY")
1512
if not _BROWSERBASE_API_KEY:
1613
raise ValueError("BROWSERBASE_API_KEY is not set in environment")

examples/e2e/test_playwright.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import pytest
55
from dotenv import load_dotenv
66
from playwright.sync_api import Playwright, sync_playwright
7+
78
from browserbase import Browserbase
89

910
from .. import (
@@ -20,9 +21,10 @@
2021
load_dotenv()
2122

2223
CI = os.getenv("CI", "false").lower() == "true"
24+
MAX_RETRIES = 3
2325

2426

25-
@pytest.fixture(scope="session")
27+
@pytest.fixture(scope="function") # Changed from "session" to "function"
2628
def playwright() -> Generator[Playwright, None, None]:
2729
with sync_playwright() as p:
2830
yield p

examples/e2e/test_selenium.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from .. import selenium_basic
2+
3+
4+
def test_selenium_basic() -> None:
5+
selenium_basic.run()

examples/playwright_captcha.py

+2-12
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
11
from playwright.sync_api import Playwright, ConsoleMessage, sync_playwright
22

3-
4-
from examples import (
5-
BROWSERBASE_API_KEY,
6-
BROWSERBASE_PROJECT_ID,
7-
BROWSERBASE_CONNECT_URL,
8-
bb,
9-
)
3+
from examples import BROWSERBASE_PROJECT_ID, bb
104

115
DEFAULT_CAPTCHA_URL = "https://www.google.com/recaptcha/api2/demo"
126
OVERRIDE_TIMEOUT = 60000 # 60 seconds, adjust as needed
@@ -19,11 +13,7 @@ def run(playwright: Playwright) -> None:
1913
assert session.status == "RUNNING", f"Session status is {session.status}"
2014

2115
# Connect to the remote session
22-
connect_url = (
23-
f"{BROWSERBASE_CONNECT_URL}?sessionId={session.id}&apiKey={BROWSERBASE_API_KEY}"
24-
)
25-
chromium = playwright.chromium
26-
browser = chromium.connect_over_cdp(connect_url)
16+
browser = playwright.chromium.connect_over_cdp(session.connect_url)
2717
context = browser.contexts[0]
2818
page = context.pages[0]
2919

examples/playwright_contexts.py

+7-16
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,15 @@
11
import time
22
from typing import Optional
33

4+
from pydantic import TypeAdapter
45
from playwright.sync_api import Cookie, Browser, Playwright, sync_playwright
56

6-
7-
from examples import (
8-
BROWSERBASE_API_KEY,
9-
BROWSERBASE_PROJECT_ID,
10-
BROWSERBASE_CONNECT_URL,
11-
bb,
12-
)
7+
from examples import BROWSERBASE_PROJECT_ID, bb
138
from browserbase.types.session_create_params import (
149
BrowserSettings,
1510
BrowserSettingsContext,
1611
)
1712

18-
1913
CONTEXT_TEST_URL = "https://www.browserbase.com"
2014
SECOND = 1000
2115

@@ -47,10 +41,11 @@ def run(playwright: Playwright) -> None:
4741
# Step 2: Creates a session with the context
4842
session = bb.sessions.create(
4943
project_id=BROWSERBASE_PROJECT_ID,
50-
browser_settings=BrowserSettings(
51-
context=BrowserSettingsContext(id=context_id, persist=True),
44+
browser_settings=TypeAdapter(BrowserSettings).validate_python(
45+
{"context": {"id": context_id, "persist": True}}
5246
),
5347
)
48+
print(session)
5449

5550
assert (
5651
session.context_id == context_id
@@ -59,9 +54,7 @@ def run(playwright: Playwright) -> None:
5954

6055
# Step 3: Populates and persists the context
6156
print(f"Populating context {context_id} during session {session_id}")
62-
connect_url = (
63-
f"{BROWSERBASE_CONNECT_URL}?sessionId={session_id}&apiKey={BROWSERBASE_API_KEY}"
64-
)
57+
connect_url = session.connect_url
6558
browser = playwright.chromium.connect_over_cdp(connect_url)
6659
page = browser.contexts[0].pages[0]
6760

@@ -108,9 +101,7 @@ def run(playwright: Playwright) -> None:
108101

109102
# Step 5: Uses context to find previous state
110103
print(f"Reusing context {context_id} during session {session_id}")
111-
connect_url = (
112-
f"{BROWSERBASE_CONNECT_URL}?sessionId={session_id}&apiKey={BROWSERBASE_API_KEY}"
113-
)
104+
connect_url = session.connect_url
114105
browser = playwright.chromium.connect_over_cdp(connect_url)
115106
page = browser.contexts[0].pages[0]
116107

examples/playwright_downloads.py

+2-10
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,7 @@
44

55
from playwright.sync_api import Playwright, sync_playwright
66

7-
8-
from examples import (
9-
BROWSERBASE_API_KEY,
10-
BROWSERBASE_PROJECT_ID,
11-
BROWSERBASE_CONNECT_URL,
12-
bb,
13-
)
7+
from examples import BROWSERBASE_PROJECT_ID, bb
148

159
download_re = re.compile(r"sandstorm-(\d{13})+\.mp3")
1610

@@ -27,9 +21,7 @@ def run(playwright: Playwright) -> None:
2721
assert session.status == "RUNNING", f"Session status is {session.status}"
2822

2923
# Connect to the remote session
30-
connect_url = (
31-
f"{BROWSERBASE_CONNECT_URL}?sessionId={session.id}&apiKey={BROWSERBASE_API_KEY}"
32-
)
24+
connect_url = session.connect_url
3325
browser = playwright.chromium.connect_over_cdp(connect_url)
3426
context = browser.contexts[0]
3527
page = context.pages[0]

examples/playwright_extensions.py

+2-8
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@
77
from playwright.sync_api import Page, Playwright, sync_playwright
88

99
from examples import (
10-
BROWSERBASE_API_KEY,
1110
BROWSERBASE_PROJECT_ID,
12-
BROWSERBASE_CONNECT_URL,
1311
bb,
1412
)
1513
from browserbase.types import Extension, SessionCreateResponse
@@ -100,9 +98,7 @@ def run(playwright: Playwright) -> None:
10098
extension_id=extension.id,
10199
)
102100

103-
browser = playwright.chromium.connect_over_cdp(
104-
f"{BROWSERBASE_CONNECT_URL}?apiKey={BROWSERBASE_API_KEY}&sessionId={session.id}"
105-
)
101+
browser = playwright.chromium.connect_over_cdp(session.connect_url)
106102
context = browser.contexts[0]
107103
page = context.pages[0]
108104
check_for_message(page, expected_message)
@@ -116,9 +112,7 @@ def run(playwright: Playwright) -> None:
116112
proxies=True,
117113
)
118114

119-
browser = playwright.chromium.connect_over_cdp(
120-
f"{BROWSERBASE_CONNECT_URL}?apiKey={BROWSERBASE_API_KEY}&sessionId={session_with_proxy.id}"
121-
)
115+
browser = playwright.chromium.connect_over_cdp(session_with_proxy.connect_url)
122116
context = browser.contexts[0]
123117
page = context.pages[0]
124118

examples/playwright_proxy.py

+6-20
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33
from playwright.sync_api import Page, Playwright, sync_playwright
44

55
from examples import (
6-
BROWSERBASE_API_KEY,
76
BROWSERBASE_PROJECT_ID,
8-
BROWSERBASE_CONNECT_URL,
97
bb,
108
)
119

@@ -26,9 +24,7 @@ def check_proxy_bytes(session_id: str) -> None:
2624
def run_enable_via_create_session(playwright: Playwright) -> None:
2725
session = bb.sessions.create(project_id=BROWSERBASE_PROJECT_ID, proxies=True)
2826

29-
browser = playwright.chromium.connect_over_cdp(
30-
f"{BROWSERBASE_CONNECT_URL}?apiKey={BROWSERBASE_API_KEY}&sessionId={session.id}"
31-
)
27+
browser = playwright.chromium.connect_over_cdp(session.connect_url)
3228

3329
context = browser.contexts[0]
3430
page = context.pages[0]
@@ -45,9 +41,7 @@ def run_enable_via_create_session(playwright: Playwright) -> None:
4541
def run_enable_via_querystring_with_created_session(playwright: Playwright) -> None:
4642
session = bb.sessions.create(project_id=BROWSERBASE_PROJECT_ID, proxies=True)
4743

48-
browser = playwright.chromium.connect_over_cdp(
49-
f"{BROWSERBASE_CONNECT_URL}?apiKey={BROWSERBASE_API_KEY}&sessionId={session.id}&enableProxy=true"
50-
)
44+
browser = playwright.chromium.connect_over_cdp(session.connect_url)
5145

5246
context = browser.contexts[0]
5347
page = context.pages[0]
@@ -84,9 +78,7 @@ def run_geolocation_country(playwright: Playwright) -> None:
8478
],
8579
)
8680

87-
browser = playwright.chromium.connect_over_cdp(
88-
f"{BROWSERBASE_CONNECT_URL}?apiKey={BROWSERBASE_API_KEY}&sessionId={session.id}"
89-
)
81+
browser = playwright.chromium.connect_over_cdp(session.connect_url)
9082

9183
context = browser.contexts[0]
9284
page = context.pages[0]
@@ -113,9 +105,7 @@ def run_geolocation_state(playwright: Playwright) -> None:
113105
],
114106
)
115107

116-
browser = playwright.chromium.connect_over_cdp(
117-
f"{BROWSERBASE_CONNECT_URL}?apiKey={BROWSERBASE_API_KEY}&sessionId={session.id}"
118-
)
108+
browser = playwright.chromium.connect_over_cdp(session.connect_url)
119109

120110
context = browser.contexts[0]
121111
page = context.pages[0]
@@ -143,9 +133,7 @@ def run_geolocation_american_city(playwright: Playwright) -> None:
143133
],
144134
)
145135

146-
browser = playwright.chromium.connect_over_cdp(
147-
f"{BROWSERBASE_CONNECT_URL}?apiKey={BROWSERBASE_API_KEY}&sessionId={session.id}"
148-
)
136+
browser = playwright.chromium.connect_over_cdp(session.connect_url)
149137

150138
context = browser.contexts[0]
151139
page = context.pages[0]
@@ -172,9 +160,7 @@ def run_geolocation_non_american_city(playwright: Playwright) -> None:
172160
],
173161
)
174162

175-
browser = playwright.chromium.connect_over_cdp(
176-
f"{BROWSERBASE_CONNECT_URL}?apiKey={BROWSERBASE_API_KEY}&sessionId={session.id}"
177-
)
163+
browser = playwright.chromium.connect_over_cdp(session.connect_url)
178164

179165
context = browser.contexts[0]
180166
page = context.pages[0]

examples/playwright_upload.py

+2-12
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,7 @@
22

33
from playwright.sync_api import Playwright, sync_playwright
44

5-
from examples import (
6-
BROWSERBASE_API_KEY,
7-
BROWSERBASE_PROJECT_ID,
8-
BROWSERBASE_CONNECT_URL,
9-
bb,
10-
)
5+
from examples import BROWSERBASE_PROJECT_ID, bb
116

127
PATH_TO_UPLOAD = Path.cwd() / "examples" / "packages" / "logo.png"
138

@@ -16,13 +11,8 @@ def run(playwright: Playwright) -> None:
1611
# Create a session
1712
session = bb.sessions.create(project_id=BROWSERBASE_PROJECT_ID)
1813

19-
# Construct the URL
20-
url = (
21-
f"{BROWSERBASE_CONNECT_URL}?apiKey={BROWSERBASE_API_KEY}&sessionId={session.id}"
22-
)
23-
2414
# Connect to the browser
25-
browser = playwright.chromium.connect_over_cdp(url)
15+
browser = playwright.chromium.connect_over_cdp(session.connect_url)
2616
context = browser.contexts[0]
2717
page = context.pages[0]
2818

examples/selenium_basic.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
from typing import Dict
2+
3+
from selenium import webdriver
4+
from selenium.webdriver.remote.remote_connection import RemoteConnection
5+
6+
from examples import BROWSERBASE_API_KEY, BROWSERBASE_PROJECT_ID, bb
7+
8+
9+
class BrowserbaseConnection(RemoteConnection):
10+
"""
11+
Manage a single session with Browserbase.
12+
"""
13+
14+
session_id: str
15+
16+
def __init__(self, session_id: str, *args, **kwargs): # type: ignore
17+
super().__init__(*args, **kwargs) # type: ignore
18+
self.session_id = session_id
19+
20+
def get_remote_connection_headers( # type: ignore
21+
self, parsed_url: str, keep_alive: bool = False
22+
) -> Dict[str, str]:
23+
headers = super().get_remote_connection_headers(parsed_url, keep_alive) # type: ignore
24+
25+
# Update headers to include the Browserbase required information
26+
headers["x-bb-api-key"] = BROWSERBASE_API_KEY
27+
headers["session-id"] = self.session_id
28+
29+
return headers # type: ignore
30+
31+
32+
def run() -> None:
33+
# Use the custom class to create and connect to a new browser session
34+
session = bb.sessions.create(project_id=BROWSERBASE_PROJECT_ID)
35+
connection = BrowserbaseConnection(session.id, session.selenium_remote_url)
36+
driver = webdriver.Remote(
37+
command_executor=connection, options=webdriver.ChromeOptions() # type: ignore
38+
)
39+
40+
# Print a bit of info about the browser we've connected to
41+
print(
42+
"Connected to Browserbase",
43+
f"{driver.name} version {driver.caps['browserVersion']}", # type: ignore
44+
)
45+
46+
try:
47+
# Perform our browser commands
48+
driver.get("https://www.sfmoma.org")
49+
print(f"At URL: {driver.current_url} | Title: {driver.title}")
50+
assert driver.current_url == "https://www.sfmoma.org/"
51+
assert driver.title == "SFMOMA"
52+
53+
finally:
54+
# Make sure to quit the driver so your session is ended!
55+
driver.quit()
56+
57+
58+
if __name__ == "__main__":
59+
run()

pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ dev-dependencies = [
5959
"rich>=13.7.1",
6060
"python-dotenv",
6161
"playwright",
62+
"selenium",
6263
]
6364

6465
[tool.rye.scripts]

0 commit comments

Comments
 (0)