Skip to content

Commit 2949d28

Browse files
committed
new sdk
1 parent 7c7e534 commit 2949d28

File tree

5 files changed

+676
-41
lines changed

5 files changed

+676
-41
lines changed

README.md

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@
1212
</p>
1313
<br/>
1414

15-
## Selenium (Python) with Browserbase
15+
## Selenium with Browserbase
16+
17+
## Introduction
18+
1619
Browserbase is the best developer platform to reliably run, manage, and monitor headless browsers.
1720

1821
Get browsers' complete control and leverage Browserbase's
@@ -22,7 +25,6 @@ and LLM data retrievals.
2225

2326
**Get started in under one minute** with Selenium.
2427

25-
2628
## Setup
2729

2830
### 1. Install dependencies
@@ -31,21 +33,30 @@ and LLM data retrievals.
3133
pip install -r requirements.txt
3234
```
3335

36+
Alternatively, we suggest using [Poetry](https://python-poetry.org/) to manage your dependencies.
37+
38+
```bash
39+
poetry install
40+
```
3441

35-
### 2. Get your Browserbase API Key:
42+
### 2. Create `.env` file:
43+
44+
```bash
45+
cp .env.example .env
46+
```
47+
48+
### 3. Get your Browserbase API Key:
3649

3750
- [Create an account](https://www.browserbase.com/sign-up) or [log in to Browserbase](https://www.browserbase.com/sign-in)
38-
- Copy your API Key and Project ID [from your Settings page](https://www.browserbase.com/settings)
51+
- Copy your API Key and Project ID [from your Settings page](https://www.browserbase.com/settings) into the `.env` file
3952

40-
### 3. Run the script:
53+
### 4. Run the script:
4154

4255
```bash
43-
BROWSERBASE_API_KEY=xxxx BROWSERBASE_PROJECT_ID==xxxx python main.py
56+
python main.py # or poetry run python main.py
4457
```
4558

46-
4759
## Further reading
4860

49-
- [See how to leverage the Session Debugger for faster development](https://docs.browserbase.com/guides/browser-remote-control#accelerate-your-local-development-with-remote-debugging)
50-
- [Learn more about Browserbase infrastructure](https://docs.browserbase.com/under-the-hood)
51-
- [Explore the Sessions API](https://docs.browserbase.com/api-reference/list-all-sessions)
61+
- [Explore the Browserbase Python SDK](https://docs.browserbase.com/sdk/python)
62+
- [Explore the Selenium Python API](https://selenium-python.readthedocs.io/api.html)

main.py

Lines changed: 56 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,67 @@
1+
from typing import Dict
2+
13
from selenium import webdriver
24
from selenium.webdriver.remote.remote_connection import RemoteConnection
3-
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
4-
import requests
5+
from browserbase import Browserbase
6+
from dotenv import load_dotenv
57
import os
68

7-
def create_session():
8-
url = 'https://www.browserbase.com/v1/sessions'
9-
headers = {'Content-Type': 'application/json', 'x-bb-api-key': os.environ["BROWSERBASE_API_KEY"]}
10-
response = requests.post(url, json={ "projectId": os.environ["BROWSERBASE_PROJECT_ID"] }, headers=headers)
11-
return response.json()['id']
9+
load_dotenv()
10+
11+
BROWSERBASE_API_KEY = os.getenv("BROWSERBASE_API_KEY")
12+
BROWSERBASE_PROJECT_ID = os.getenv("BROWSERBASE_PROJECT_ID")
13+
14+
bb = Browserbase(api_key=BROWSERBASE_API_KEY)
15+
16+
17+
class BrowserbaseConnection(RemoteConnection):
18+
"""
19+
Manage a single session with Browserbase.
20+
"""
21+
22+
session_id: str
23+
24+
def __init__(self, session_id: str, *args, **kwargs): # type: ignore
25+
super().__init__(*args, **kwargs) # type: ignore
26+
self.session_id = session_id
27+
28+
def get_remote_connection_headers( # type: ignore
29+
self, parsed_url: str, keep_alive: bool = False
30+
) -> Dict[str, str]:
31+
headers = super().get_remote_connection_headers(parsed_url, keep_alive) # type: ignore
32+
33+
# Update headers to include the Browserbase required information
34+
headers["x-bb-api-key"] = BROWSERBASE_API_KEY
35+
headers["session-id"] = self.session_id
36+
37+
return headers # type: ignore
1238

1339

14-
class CustomRemoteConnection(RemoteConnection):
15-
_session_id = None
40+
def run() -> None:
41+
# Use the custom class to create and connect to a new browser session
42+
session = bb.sessions.create(project_id=BROWSERBASE_PROJECT_ID)
43+
connection = BrowserbaseConnection(session.id, session.selenium_remote_url)
44+
driver = webdriver.Remote(
45+
command_executor=connection, options=webdriver.ChromeOptions() # type: ignore
46+
)
1647

17-
def __init__(self, remote_server_addr: str, session_id: str):
18-
super().__init__(remote_server_addr)
19-
self._session_id = session_id
48+
# Print a bit of info about the browser we've connected to
49+
print(
50+
"Connected to Browserbase",
51+
f"{driver.name} version {driver.caps['browserVersion']}", # type: ignore
52+
)
2053

21-
def get_remote_connection_headers(self, parsed_url, keep_alive=False):
22-
headers = super().get_remote_connection_headers(parsed_url, keep_alive)
23-
headers.update({'x-bb-api-key': os.environ["BROWSERBASE_API_KEY"]})
24-
headers.update({'session-id': self._session_id})
25-
return headers
54+
try:
55+
# Perform our browser commands
56+
driver.get("https://www.sfmoma.org")
57+
print(f"At URL: {driver.current_url} | Title: {driver.title}")
58+
assert driver.current_url == "https://www.sfmoma.org/"
59+
assert driver.title == "SFMOMA"
2660

61+
finally:
62+
# Make sure to quit the driver so your session is ended!
63+
driver.quit()
2764

28-
def run():
29-
session_id = create_session()
30-
custom_conn = CustomRemoteConnection('http://connect.browserbase.com/webdriver', session_id)
31-
options = webdriver.ChromeOptions()
32-
options.debugger_address = "localhost:9223"
33-
driver = webdriver.Remote(custom_conn, options=options)
34-
driver.get("https://www.browserbase.com")
35-
get_title = driver.title
36-
print(get_title)
37-
# Make sure to quit the driver so your session is ended!
38-
driver.quit()
3965

40-
run()
66+
if __name__ == "__main__":
67+
run()

0 commit comments

Comments
 (0)