Skip to main content

Selenium

Using Surfsky with Selenium WebDriver

Installation

pip install selenium httpx

Basic Example

import httpx
from selenium import webdriver
from selenium.webdriver.remote.remote_connection import RemoteConnection
from selenium.webdriver.chrome.options import Options

# Configuration
API_BASE = 'http://api.octo-cloud.local'
API_TOKEN = 'your-api-token-here'

# Custom connection class for authentication
class SurfskyRemoteConnection(RemoteConnection):
def __init__(self, server_url: str, api_token: str):
super().__init__(server_url)
self._api_token = api_token

def get_remote_connection_headers(self, parsed_url, keep_alive=False):
headers = super().get_remote_connection_headers(parsed_url, keep_alive)
headers['X-Cloud-Api-Token'] = self._api_token
return headers

# Step 1: Create a browser profile with ChromeDriver enabled
headers = {
'X-Cloud-Api-Token': API_TOKEN,
'Content-Type': 'application/json'
}

with httpx.Client() as client:
response = client.post(
url=f"{API_BASE}/profiles/one_time",
headers=headers,
json={
"browser_settings": {
"inactive_kill_timeout": 120
},
"enable_chromedriver": True # Required for Selenium
}
)
internal_uuid = response.json()['internal_uuid']

# Step 2: Connect Selenium WebDriver
webdriver_url = f'{API_BASE}/chromedriver/{internal_uuid}'
custom_conn = SurfskyRemoteConnection(webdriver_url, API_TOKEN)

chrome_options = Options()
chrome_options.add_experimental_option('w3c', True)

driver = webdriver.Remote(
command_executor=custom_conn,
options=chrome_options
)

# Step 3: Use the browser
driver.get('https://www.google.com')
print(f"Page title: {driver.title}")
print(f"Current URL: {driver.current_url}")

# Take a screenshot
driver.save_screenshot('screenshot.png')

# Clean up
driver.quit()

# Step 4: Stop the profile
with httpx.Client() as client:
client.post(
url=f"{API_BASE}/profiles/{internal_uuid}/stop",
headers=headers
)

Key Points

  1. Enable ChromeDriver: Set enable_chromedriver: true when creating the profile
  2. Custom Connection: Use SurfskyRemoteConnection to add authentication headers
  3. WebDriver URL: Connect to /chromedriver/{internal_uuid} endpoint
  4. Cleanup: Always stop the profile after use