Selenium
How to use in Selenium
- Download the corresponding Webdriver. (https://googlechromelabs.github.io/chrome-for-testing/#stable)
- Launch nstbrowser agent client, the client will listen on port:
8848
- Get the remote debugging address of the browser:
debuggerAddress
. - Connect to the browser through selenium.
1. LaunchExistBrowser
::: tip URLws://localhost:8848/devtool/launch/{profileId}?x-api-key={x-api-key}&config={config}
- Connect to or start an existing browser,you need to create the corresponding profile in advance
- Support custom config
:::
import puppeteer from 'puppeteer-core';
// LaunchExistBrowser: Connect to or start an existing browser
// You need to create the corresponding profile in advance
// Support custom config
async function launchAndConnectToBrowser(profileId) {
const host = 'localhost:8848';
const apiKey = 'your api key';
const config = {
headless: true, // support: true, 'new'
autoClose: true,
};
const query = new URLSearchParams({
'x-api-key': apiKey, // required
config: encodeURIComponent(JSON.stringify((config))),
});
const browserWSEndpoint = `ws://${host}/devtool/launch/${profileId}?${query.toString()}`;
console.log('browserWSEndpoint: ', browserWSEndpoint);
await execPuppeteer(browserWSEndpoint);
}
launchAndConnectToBrowser('your profileId').then();
2. CreateAndConnectToBrowser
- Create a new Profile based on config and launch the browser
- Support custom config
import json
from urllib.parse import quote
from urllib.parse import urlencode
import requests
from requests.exceptions import HTTPError
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
# TODO coming soon
# create_and_connect_to_browser: launch new browser and connect
# Create a new Profile based on config and launch the browser
# Support custom config
def create_and_connect_to_browser():
host = '127.0.0.1'
api_key = 'your apiKey'
config = {
'once': True,
'headless': True, // support: True, 'new'
'autoClose': True,
'remoteDebuggingPort': 9222,
'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', # userAgent supportted since v0.15.0
'fingerprint': { # required
'name': 'custom browser',
'platform': 'windows', # support: windows, mac, linux
'kernel': 'chromium', # only support: chromium
'kernelMilestone': '113', # support: 113, 115, 118, 120
'hardwareConcurrency': 4, # support: 2, 4, 8, 10, 12, 14, 16
'deviceMemory': 4, # support: 2, 4, 8
'proxy': '', # input format: schema://user:password@host:port eg: http://user:password@localhost:8080
}
}
query = urlencode({
'x-api-key': api_key, # required
'config': quote(json.dumps(config))
})
url = f'http://{host}:8848/devtool/launch?{query}'
print('devtool url: ' + url)
port = get_debugger_port(url)
debugger_address = f'{host}:{port}'
print("debugger_address: " + debugger_address)
exec_selenium(debugger_address)
create_and_connect_to_browser()
3. Config parameters notes
Parameter | Type | Description | |
---|---|---|---|
config.once | Boolean | Disposable browser that does not create a Profile and automatically closes after execution; (only supported by "CreateAndConnectToBrowser") | |
config.headless | Boolean | String | true: enable headless; "new": enable new headless mode; difference reference https://developer.chrome.com/docs/chromium/new-headless. and automatically close after execution | |
config.autoClose | Boolean | Whether to automatically close the connection after the browser is closed | |
config.timedCloseSec | Number | Timed close (s) | |
config.remoteDebuggingPort | Number | Remote debugging port | |
config.userAgent | String | UserAgent | |
config.fingerprint | Object | Browser fingerprint configuration; (only supported by "CreateAndConnectToBrowser") | |
name | String | Browser name | |
platform | String | Operating system type (supported: windows, mac, linux) | |
kernel | String | Kernel type (only supported: chromium) | |
kernelMilestone | String | Kernel version (supported: 113, 115, 118, 120) | |
hardwareConcurrency | Number | CPU core count (supported: 2, 4, 8, 10, 12, 14, 16) | |
deviceMemory | Number | Device memory size (supported: 2, 4, 8) | |
proxy | String | Proxy server address and port number (format: schema://user:password@host:port, e.g. http://user/:password@localhost:8080/) |
4. Common Code
# get_debugger_port: Get the debugger port
def get_debugger_port(url: str):
try:
resp = requests.get(url).json()
if resp['data'] is None:
raise Exception(resp['msg'])
port = resp['data']['port']
return port
except HTTPError:
raise Exception(HTTPError.response)
def exec_selenium(debugger_address: str):
options = webdriver.ChromeOptions()
options.add_experimental_option("debuggerAddress", debugger_address)
# Replace with the corresponding version of WebDriver path.
chrome_driver_path = r'./webdriver/chromedriver_113.exe'
service = ChromeService(executable_path=chrome_driver_path)
driver = webdriver.Chrome(service=service, options=options)
driver.get("https://nstbrowser.io")
driver.save_screenshot('screenshot.png')
driver.close()
driver.quit()
Modified at a month ago