|
| 1 | +from examples import bb, BROWSERBASE_PROJECT_ID, BROWSERBASE_API_KEY |
| 2 | +from browserbase.types import SessionCreateResponse |
| 3 | +from selenium import webdriver |
| 4 | +from selenium.webdriver.remote.webdriver import WebDriver |
| 5 | +from selenium.webdriver.remote.remote_connection import RemoteConnection |
| 6 | + |
| 7 | + |
| 8 | +class BrowserbaseConnection(RemoteConnection): |
| 9 | + """ |
| 10 | + Manage a single session with Browserbase. |
| 11 | + """ |
| 12 | + |
| 13 | + browserbase_session: SessionCreateResponse |
| 14 | + |
| 15 | + def __init__(self, *args, **kwargs): |
| 16 | + self.browserbase_session = bb.sessions.create(project_id=BROWSERBASE_PROJECT_ID) |
| 17 | + super().__init__(*args, **kwargs) |
| 18 | + |
| 19 | + def get_remote_connection_headers(self, parsed_url, keep_alive=False): |
| 20 | + headers = super().get_remote_connection_headers(parsed_url, keep_alive) |
| 21 | + |
| 22 | + # Update headers to include the Browserbase required information |
| 23 | + headers["x-bb-api-key"] = BROWSERBASE_API_KEY |
| 24 | + headers["session-id"] = self.browserbase_session.id |
| 25 | + |
| 26 | + return headers |
| 27 | + |
| 28 | + |
| 29 | +def run(driver: WebDriver): |
| 30 | + # Instruct the browser to go to the SF MOMA page |
| 31 | + driver.get("https://www.sfmoma.org") |
| 32 | + |
| 33 | + # Print out a bit of info about the page it landed on |
| 34 | + print(f"{driver.current_url=} | {driver.title=}") |
| 35 | + |
| 36 | + ... |
| 37 | + |
| 38 | + |
| 39 | +# Use the custom class to create and connect to a new browser session |
| 40 | +connection = BrowserbaseConnection("http://connect.browserbase.com/webdriver") |
| 41 | +driver = webdriver.Remote(connection, options=webdriver.ChromeOptions()) |
| 42 | + |
| 43 | +# Print a bit of info about the browser we've connected to |
| 44 | +print( |
| 45 | + "Connected to Browserbase", |
| 46 | + f"{driver.name} version {driver.caps['browserVersion']}", |
| 47 | +) |
| 48 | + |
| 49 | +try: |
| 50 | + # Perform our browser commands |
| 51 | + run(driver) |
| 52 | + |
| 53 | +finally: |
| 54 | + # Make sure to quit the driver so your session is ended! |
| 55 | + driver.quit() |
0 commit comments