SeleniumBase MCP
OfficialThis server provides a persistent SeleniumBase Pure CDP browser-automation session controlled through MCP tools.
Start and close a Chrome/Chromium browser with options for URL, headless/headed, incognito/guest, ad blocking, proxy, and executable path.
Navigate URLs, manage back/forward/reload history, and open/list/switch/close browser tabs.
Inspect page metadata, visible text, HTML, URLs, element matches, and HTML attributes.
Check, wait for, and assert element/text/title/URL conditions.
Interact with pages by clicking elements, typing/filling/clearing fields, selecting native dropdown options, hovering, dragging/dropping, focusing, highlighting, and scrolling.
Manage cookies and localStorage/sessionStorage.
Execute arbitrary JavaScript in the page context.
Attempt to solve supported CAPTCHAs such as Cloudflare Turnstile, reCAPTCHA, hCaptcha, DataDome Slider, and FriendlyCaptcha.
Save the current page as a screenshot, HTML source, or PDF.
Manage browser window geometry and state.
Provides a CAPTCHA solving tool that can attempt to interact with Cloudflare Turnstile challenges during browser automation, using CDP-based clicks to avoid detection.
Provides a CAPTCHA solving tool that can attempt to interact with Google reCAPTCHA challenges during browser automation, using CDP-based clicks to avoid detection.
Launches, controls, and automates Google Chrome (or Chromium) browser sessions via SeleniumBase Pure CDP Mode, enabling navigation, element interaction, page content retrieval, and stealth browser automation.
š Learn from over 200 end-to-end tests in SeleniumBase/examples/.
Examples that start/end withtest run with pytest.
Other examples run directly with raw python.
š This example uses seleniumbase sb_cdp (Pure CDP Mode):(It shows some basic methods and bypasses a Cloudflare Turnstile)
from seleniumbase import sb_cdp
sb = sb_cdp.Chrome() # Launch a stealth browser
sb.goto("https://www.planetminecraft.com/account")
sb.type('[name="email"]', "Test123")
sb.type('[name="password"]', "Pass")
sb.click("input#autologin") # Uncheck a checkbox
sb.solve_captcha() # (fallback if not automatic)
sb.assert_element('input[name="login"]')
sb.assert_element_not_visible("input[disabled]")
sb.sleep(1) # (see the live demo more easily)
sb.quit()ā sb.solve_captcha() handles CAPTCHAs that aren't bypassed automatically.(If called when there's no CAPTCHA on the page, then nothing happens / no-op.)
ā¹ļø sb.assert_* methods wait up to 7 seconds for the expected condition.(Raises an exception if the condition isn't met in time.)
from seleniumbase import sb_cdp
sb = sb_cdp.Chrome(fast=True)
sb.goto("https://hn.algolia.com/?query=seleniumbase")
elements = sb.find_elements("div.Story_title > a")
for element in elements:
print("--> " + element.text)
sb.save_as_pdf("sb_news.pdf", folder="./downloaded_files/")
print("*** PDF saved to: ./downloaded_files/sb_news.pdf")python raw_cdp_yc_news.pyfrom seleniumbase import SB
with SB(uc=True, test=True, locale="en") as sb:
sb.activate_cdp_mode()
sb.goto("https://gitlab.com/users/sign_in")
sb.sleep(2)
sb.solve_captcha()
sb.highlight('h1:contains("GitLab")')
sb.highlight('button:contains("Sign in")')python raw_gitlab.pypython SCRIPT.py --chromium # Use the unbranded Chromium browser
python SCRIPT.py --cft # Use Chrome-for-testing
python SCRIPT.py --edge # Use Microsoft Edge
python SCRIPT.py --brave # Use Brave browserGoogle Chrome is the default browser. Only unbranded Chromium and Chrome-for-Testing get downloaded automatically if not already present on the system.
The Chromium browser can also be set via method args, eg: cft=True, use_chromium=True, browser="edge", browser="brave", etc. Eg:
sb = sb_cdp.Chrome(use_chromium=True)from seleniumbase import BaseCase
BaseCase.main(__name__, __file__) # Call pytest
class MyTestClass(BaseCase):
def test_swag_labs(self):
self.goto("https://www.saucedemo.com")
self.type("#user-name", "standard_user")
self.type("#password", "secret_sauce\n")
self.assert_element("div.inventory_list")
self.click('button[name*="backpack"]')
self.click("#shopping_cart_container a")
self.assert_text("Backpack", "div.cart_item")
self.click("button#checkout")
self.type("input#first-name", "SeleniumBase")
self.type("input#last-name", "Automation")
self.type("input#postal-code", "77123")
self.click("input#continue")
self.click("button#finish")
self.assert_text("Thank you for your order!")pytest test_get_swag.pyš„· For stealth with pytest, add --uc as a command-line option.
from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)
class CoffeeCartTest(BaseCase):
def test_coffee_cart(self):
self.goto("https://seleniumbase.io/coffee/")
self.assert_title("Coffee Cart")
self.assert_element('button:contains("Total: $0.00")')
self.click('div[data-sb="Cappuccino"]')
self.assert_exact_text("cart (1)", 'a[aria-label="Cart page"]')
self.click('div[data-sb="Flat-White"]')
self.assert_exact_text("cart (2)", 'a[aria-label="Cart page"]')
self.click('div[data-sb="Cafe-Latte"]')
self.assert_exact_text("cart (3)", 'a[aria-label="Cart page"]')
self.click('a[aria-label="Cart page"]')
self.assert_exact_text("Total: $53.00", "button.pay")
self.click("button.pay")
self.type("input#name", "Selenium Coffee")
self.type("input#email", "test@test.test")
self.click("button#submit-payment")
self.assert_text("Thanks for your purchase.", "#app .success")pytest test_coffee_cart.py --demopytest test_demo_site.pyEasy to type, click, select, toggle, drag & drop, and more.
š For more scripts, see the SeleniumBase/examples/ folder.
(Note that "Regular Mode" also supports Safari/WebKit and Firefox/Gecko.)
from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)
class TestSimpleLogin(BaseCase):
def test_simple_login(self):
self.goto("seleniumbase.io/simple/login")
self.type("#username", "demo_user")
self.type("#password", "secret_pass")
self.click('a:contains("Sign in")')
self.assert_exact_text("Welcome!", "h1")
self.assert_element("img#image1")
self.highlight("#image1")
self.click_link("Sign out")
self.assert_text("signed out", "#top_message")from seleniumbase import SB
with SB() as sb:
sb.goto("seleniumbase.io/simple/login")
sb.type("#username", "demo_user")
sb.type("#password", "secret_pass")
sb.click('a:contains("Sign in")')
sb.assert_exact_text("Welcome!", "h1")
sb.assert_element("img#image1")
sb.highlight("#image1")
sb.click_link("Sign out")
sb.assert_text("signed out", "#top_message")from seleniumbase import Driver
driver = Driver()
try:
driver.goto("seleniumbase.io/simple/login")
driver.type("#username", "demo_user")
driver.type("#password", "secret_pass")
driver.click('a:contains("Sign in")')
driver.assert_exact_text("Welcome!", "h1")
driver.assert_element("img#image1")
driver.highlight("#image1")
driver.click_link("Sign out")
driver.assert_text("signed out", "#top_message")
finally:
driver.quit()šµ Add Python and Git to your System PATH.
šµ Using a Python virtual env is recommended.
šµ How to install seleniumbase from PyPI using pip:
pip install seleniumbase(Add
--upgradeOR-Uto upgrade SeleniumBase.)(Add
--force-reinstallto upgrade indirect packages.)
šµ How to install seleniumbase from a GitHub clone:
git clone https://github.com/seleniumbase/SeleniumBase.git
cd SeleniumBase/
pip install -e .šµ How to upgrade an existing install from a GitHub clone:
git pull
pip install -e .šµ Type seleniumbase or sbase to verify that SeleniumBase was installed successfully:
___ _ _ ___
/ __| ___| |___ _ _ (_)_ _ _ __ | _ ) __ _ ______
\__ \/ -_) / -_) ' \| | \| | ' \ | _ \/ _` (_-< -_)
|___/\___|_\___|_||_|_|\_,_|_|_|_\|___/\__,_/__|___|
----------------------------------------------------
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā®
ā * USAGE: "seleniumbase [COMMAND] [PARAMETERS]" ā
ā * OR: "sbase [COMMAND] [PARAMETERS]" ā
ā ā
ā COMMANDS: PARAMETERS / DESCRIPTIONS: ā
ā get / install [DRIVER_NAME] [OPTIONS] ā
ā methods (List common Python methods) ā
ā options (List common pytest options) ā
ā behave-options (List common behave options) ā
ā gui / commander [OPTIONAL PATH or TEST FILE] ā
ā behave-gui (SBase Commander for Behave) ā
ā caseplans [OPTIONAL PATH or TEST FILE] ā
ā mkdir [DIRECTORY] [OPTIONS] ā
ā mkfile [FILE.py] [OPTIONS] ā
ā mkrec / codegen [FILE.py] [OPTIONS] ā
ā recorder (Open Recorder Desktop App.) ā
ā record (If args: mkrec. Else: App.) ā
ā mkpres [FILE.py] [LANG] ā
ā mkchart [FILE.py] [LANG] ā
ā print [FILE] [OPTIONS] ā
ā translate [SB_FILE.py] [LANG] [ACTION] ā
ā convert [WEBDRIVER_UNITTEST_FILE.py] ā
ā extract-objects [SB_FILE.py] ā
ā inject-objects [SB_FILE.py] [OPTIONS] ā
ā objectify [SB_FILE.py] [OPTIONS] ā
ā revert-objects [SB_FILE.py] [OPTIONS] ā
ā encrypt / obfuscate ā
ā decrypt / unobfuscate ā
ā proxy (Start a basic proxy server) ā
ā download server (Get Selenium Grid JAR file) ā
ā grid-hub [start|stop] [OPTIONS] ā
ā grid-node [start|stop] --hub=[HOST/IP] ā
ā ā
ā * EXAMPLE => "sbase get chromedriver stable" ā
ā * For command info => "sbase help [COMMAND]" ā
ā * For info on all commands => "sbase --help" ā
ā°āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāÆā
SeleniumBase automatically downloads webdrivers as needed, such as chromedriver.
*** Getting chromedriver 154.0.8037.57 (Latest Stable)
Downloading chromedriver-mac-arm64.zip from:
https://storage.googleapis.com/chrome-for-testing-public/154.0.8037.57/mac-arm64/chromedriver-mac-arm64.zip ...
Download Complete!
Extracting ['chromedriver'] from chromedriver-mac-arm64.zip ...
Unzip Complete!
The file [chromedriver] was saved to:
~/github/SeleniumBase/seleniumbase/drivers/
chromedriver
[chromedriver 154.0.8037.57] is ready for use!šµ If you've cloned SeleniumBase, you can run tests from the examples/ folder.
cd examples/
pytest my_first_test.pyfrom seleniumbase import BaseCase
BaseCase.main(__name__, __file__)
class MyTestClass(BaseCase):
def test_swag_labs(self):
self.goto("https://www.saucedemo.com")
self.type("#user-name", "standard_user")
self.type("#password", "secret_sauce\n")
self.assert_element("div.inventory_list")
self.assert_exact_text("Products", "span.title")
self.click('button[name*="backpack"]')
self.click("#shopping_cart_container a")
self.assert_exact_text("Your Cart", "span.title")
self.assert_text("Backpack", "div.cart_item")
self.click("button#checkout")
self.type("#first-name", "SeleniumBase")
self.type("#last-name", "Automation")
self.type("#postal-code", "77123")
self.click("input#continue")
self.assert_text("Checkout: Overview")
self.assert_text("Backpack", "div.cart_item")
self.assert_text("29.99", "div.inventory_item_price")
self.click("button#finish")
self.assert_exact_text("Thank you for your order!", "h2")
self.assert_element('img[alt="Pony Express"]')
self.js_click("a#logout_sidebar_link")
self.assert_element("div#login_button_container")By default, CSS Selectors are used for finding page elements.
If you're new to CSS Selectors, games like CSS Diner can help you learn.
For more reading, here's an advanced guide on CSS attribute selectors.
self.goto(url) # Navigate the browser window to the URL.
self.open(url) # Same as `self.goto(url)`
self.activate_cdp_mode() # Activate CDP Mode from UC Mode.
self.type(selector, text) # Update the field with the text.
self.click(selector) # Click the element with the selector.
self.click_link(link_text) # Click the link containing text.
self.go_back() # Navigate back to the previous URL.
self.select_option_by_text(dropdown_selector, option)
self.hover_and_click(hover_selector, click_selector)
self.drag_and_drop(drag_selector, drop_selector)
self.get_text(selector) # Get the text from the element.
self.get_current_url() # Get the URL of the current page.
self.get_page_source() # Get the HTML of the current page.
self.get_attribute(selector, attribute) # Get element attribute.
self.get_title() # Get the title of the current page.
self.switch_to_frame(frame) # Switch into the iframe container.
self.switch_to_default_content() # Leave the iframe container.
self.open_new_window() # Open a new window in the same browser.
self.switch_to_window(window) # Switch to the browser window.
self.switch_to_default_window() # Switch to the original window.
self.get_new_driver(OPTIONS) # Open a new driver with OPTIONS.
self.switch_to_driver(driver) # Switch to the browser driver.
self.switch_to_default_driver() # Switch to the original driver.
self.wait_for_element(selector) # Wait until element is visible.
self.is_element_visible(selector) # Return element visibility.
self.is_text_visible(text, selector) # Return text visibility.
self.sleep(seconds) # Do nothing for the given amount of time.
self.save_screenshot(name) # Save a screenshot in .png format.
self.assert_element(selector) # Verify the element is visible.
self.assert_text(text, selector) # Verify text in the element.
self.assert_exact_text(text, selector) # Verify text is exact.
self.assert_title(title) # Verify the title of the web page.
self.assert_downloaded_file(file) # Verify file was downloaded.
self.assert_no_404_errors() # Verify there are no broken links.
self.assert_no_js_errors() # Verify there are no JS errors.šµ For the complete list of SeleniumBase methods, see: Method Summary
self.type("input", "dogs\n") # (The "\n" presses ENTER)Most SeleniumBase scripts can be run with pytest, pynose, or pure python. Not all test runners can run all test formats. For example, tests that use the sb pytest fixture can only be run with pytest. (See Syntax Formats) There's also a Gherkin test format that runs with behave.
pytest coffee_cart_tests.py --rs
pytest test_sb_fixture.py --demo
pytest test_suite.py --rs --html=report.html --dashboard
pynose basic_test.py --mobile
pynose test_suite.py --headless --report --show-report
python raw_sb.py
python raw_test_scripts.py
behave realworld.feature
behave calculator.feature -D rs -D dashboardPython files that start with
test_or end with_test.py.Python methods that start with
test_.
With a SeleniumBase pytest.ini file present, you can modify default discovery settings. The Python class name can be anything because seleniumbase.BaseCase inherits unittest.TestCase to trigger autodiscovery.
pytest --co -qpytest [FILE_NAME.py]::[CLASS_NAME]::[METHOD_NAME]
pynose [FILE_NAME.py]:[CLASS_NAME].[METHOD_NAME]ā SeleniumBase supports all major browsers and operating systems:
ā SeleniumBase works on all popular CI/CD platforms:
šµ Demo Mode helps you see what a test is doing. If a test is moving too fast for your eyes, run it in Demo Mode to pause the browser briefly between actions, highlight page elements being acted on, and display assertions:
pytest my_first_test.py --demošµ time.sleep(seconds) can be used to make a test wait at a specific spot:
import time; time.sleep(3) # Do nothing for 3 seconds.šµ Debug Mode with Python's built-in pdb library helps you debug tests:
breakpoint() # Shortcut for "import pdb; pdb.set_trace()"(
pdbcommands:n,c,s,u,d=>next,continue,step,up,down)
šµ To pause an active test that throws an exception or error, (and keep the browser window open while Debug Mode begins in the console), add --pdb as a pytest option:
pytest test_fail.py --pdbšµ To start tests in Debug Mode, add --trace as a pytest option:
pytest test_coffee_cart.py --traceā Here are some useful command-line options that come with pytest:
-v # Verbose mode. Prints the full name of each test and shows more details.
-q # Quiet mode. Print fewer details in the console output when running tests.
-x # Stop running the tests after the first failure is reached.
--html=report.html # Creates a detailed pytest-html report after tests finish.
--co | --collect-only # Show what tests would get run. (Without running them)
--co -q # (Both options together!) - Do a dry run with full test names shown.
-n=NUM # Multithread the tests using that many threads. (Speed up test runs!)
-s # See print statements. (Should be on by default with pytest.ini present.)
--junit-xml=report.xml # Creates a junit-xml report after tests finish.
--pdb # If a test fails, enter Post Mortem Debug Mode. (Don't use with CI!)
--trace # Enter Debug Mode at the beginning of each test. (Don't use with CI!)
-m=MARKER # Run tests with the specified pytest marker.ā SeleniumBase provides additional pytest command-line options for tests:
--browser=BROWSER # (The web browser to use. Default: "chrome".)
--chrome # (Shortcut for "--browser=chrome". On by default.)
--edge # (Shortcut for "--browser=edge".)
--firefox # (Shortcut for "--browser=firefox".)
--safari # (Shortcut for "--browser=safari".)
--opera # (Shortcut for "--browser=opera".)
--brave # (Shortcut for "--browser=brave".)
--comet # (Shortcut for "--browser=comet".)
--chromium # (Shortcut for using base `Chromium`)
--settings-file=FILE # (Override default SeleniumBase settings.)
--env=ENV # (Set the test env. Access with "self.env" in tests.)
--account=STR # (Set account. Access with "self.account" in tests.)
--data=STRING # (Extra test data. Access with "self.data" in tests.)
--var1=STRING # (Extra test data. Access with "self.var1" in tests.)
--var2=STRING # (Extra test data. Access with "self.var2" in tests.)
--var3=STRING # (Extra test data. Access with "self.var3" in tests.)
--variables=DICT # (Extra test data. Access with "self.variables".)
--user-data-dir=DIR # (Set the Chrome user data directory to use.)
--protocol=PROTOCOL # (The Selenium Grid protocol: http|https.)
--server=SERVER # (The Selenium Grid server/IP used for tests.)
--port=PORT # (The Selenium Grid port used by the test server.)
--cap-file=FILE # (The web browser's desired capabilities to use.)
--cap-string=STRING # (The web browser's desired capabilities to use.)
--proxy=SERVER:PORT # (Connect to a proxy server:port as tests are running)
--proxy=USERNAME:PASSWORD@SERVER:PORT # (Use an authenticated proxy server)
--proxy-bypass-list=STRING # (";"-separated hosts to bypass, Eg "*.foo.com")
--proxy-pac-url=URL # (Connect to a proxy server using a PAC_URL.pac file.)
--proxy-pac-url=USERNAME:PASSWORD@URL # (Authenticated proxy with PAC URL.)
--proxy-driver # (If a driver download is needed, will use: --proxy=PROXY.)
--multi-proxy # (Allow multiple authenticated proxies when multi-threaded.)
--agent=STRING # (Modify the web browser's User-Agent string.)
--mobile # (Use the mobile device emulator while running tests.)
--metrics=STRING # (Set mobile metrics: "CSSWidth,CSSHeight,PixelRatio".)
--chromium-arg="ARG=N,ARG2" # (Set Chromium args, ","-separated, no spaces.)
--firefox-arg="ARG=N,ARG2" # (Set Firefox args, comma-separated, no spaces.)
--firefox-pref=SET # (Set a Firefox preference:value set, comma-separated.)
--extension-zip=ZIP # (Load a Chrome Extension .zip|.crx, comma-separated.)
--extension-dir=DIR # (Load a Chrome Extension directory, comma-separated.)
--disable-features="F1,F2" # (Disable features, comma-separated, no spaces.)
--binary-location=PATH # (Set path of the Chromium browser binary to use.)
--driver-version=VER # (Set the chromedriver or uc_driver version to use.)
--sjw # (Skip JS Waits for readyState to be "complete" or Angular to load.)
--wfa # (Wait for AngularJS to be done loading after specific web actions.)
--pls=PLS # (Set pageLoadStrategy on Chrome: "normal", "eager", or "none".)
--headless # (Use headless mode. Linux uses this mode by default.)
--chs # (Use Chrome-Headless-Shell, a limited Chrome without stealth.)
--headed # (Run tests in headed/GUI mode on Linux OS, where not default.)
--incognito # (Enable Chrome's Incognito mode.)
--guest # (Enable Chrome's Guest mode.)
--uc # (Use undetected-chromedriver to evade bot-detection.)
--uc-cdp-events # (Capture CDP events in UC Mode. NOT related to CDP Mode.)
--log-cdp # ("goog:loggingPrefs", {"performance": "ALL", "browser": "ALL"})
--remote-debug # (Sync to Chrome Remote Debugger chrome://inspect/#devices)
--xvfb # (Run tests using the Xvfb virtual display server on Linux OS.)
--xvfb-metrics=STRING # (Set Xvfb display size on Linux: "Width,Height".)
--locale=LOCALE_CODE # (Set the Language Locale Code for the web browser.)
--interval=SECONDS # (The autoplay interval for presentations & tour steps)
--start-page=URL # (The starting URL for the web browser when tests begin.)
--archive-logs # (Archive existing log files instead of deleting them.)
--archive-downloads # (Archive old downloads instead of deleting them.)
--time-limit=SECONDS # (Safely fail any test that exceeds the time limit.)
--fast # (Run the automation at full speed. May impact stealth.)
--slow # (Slow down the automation. Faster than using Demo Mode.)
--demo # (Slow down and visually see test actions as they occur.)
--demo-sleep=SECONDS # (Set the wait time after Slow & Demo Mode actions.)
--highlights=NUM # (Number of highlight animations for Demo Mode actions.)
--message-duration=SECONDS # (The time length for Messenger alerts.)
--check-js # (Check for JavaScript errors after page loads.)
--ad-block # (Block some types of display ads from loading.)
--host-resolver-rules=RULES # (Set host-resolver-rules, comma-separated.)
--block-images # (Block images from loading during tests.)
--do-not-track # (Indicate to websites that you don't want to be tracked.)
--verify-delay=SECONDS # (The delay before MasterQA verification checks.)
--ee | --esc-end # (Lets the user end the current test via the ESC key.)
--recorder # (Enables the Recorder for turning browser actions into code.)
--rec-sb-mgr # (A Recorder Mode that generates SB() context manager code.)
--rec-sb-cdp # (A Recorder Mode that generates Pure CDP Mode sb_cdp code.)
--rec-behave # (Same as Recorder Mode, but also generates behave-gherkin.)
--rec-sleep # (If the Recorder is enabled, also records self.sleep calls.)
--rec-print # (If the Recorder is enabled, prints output after tests end.)
--disable-cookies # (Disable Cookies on websites. Pages might break!)
--disable-js # (Disable JavaScript on websites. Pages might break!)
--disable-csp # (Disable the Content Security Policy of websites.)
--disable-ws # (Disable Web Security on Chromium-based browsers.)
--enable-ws # (Enable Web Security on Chromium-based browsers.)
--enable-sync # (Enable "Chrome Sync" on websites.)
--ftrace | --final-trace # (Debug Mode after each test. Don't use with CI!)
--dashboard # (Enable the SeleniumBase Dashboard. Saved at: dashboard.html)
--dash-title=STRING # (Set the title shown for the generated dashboard.)
--enable-3d-apis # (Enables WebGL and 3D APIs.)
--swiftshader # (Chrome "--use-gl=angle" / "--use-angle=swiftshader-webgl")
--dark # (Enable Chrome's Dark mode.)
--devtools # (Open Chrome's DevTools when the browser opens.)
--rs | --reuse-session # (Reuse browser session for all tests.)
--rcs | --reuse-class-session # (Reuse session for tests in class.)
--crumbs # (Delete all cookies between tests reusing a session.)
--no-tt # (Skips "--test-type" when using Proxy Mode. Adds stealth.)
--disable-beforeunload # (Disable the "beforeunload" event on Chrome.)
--window-position=X,Y # (Set the browser's starting window position.)
--window-size=WIDTH,HEIGHT # (Set the browser's starting window size.)
--maximize # (Start tests with the browser window maximized.)
--screenshot # (Save a screenshot at the end of each test.)
--no-screenshot # (No screenshots saved unless tests directly ask it.)
--visual-baseline # (Set the visual baseline for Visual/Layout tests.)
--external-pdf # (Set Chromium "plugins.always_open_pdf_externally":True.)
--timeout-multiplier=MULTIPLIER # (Multiplies the default timeout values.)
--list-fail-page # (After each failing test, list the URL of the failure.)(See the full list of command-line option definitions here. For detailed examples of command-line options, see customizing_test_runs.md)
šµ During test failures, logs and screenshots from the most recent test run will get saved to the latest_logs/ folder. Those logs will get moved to archived_logs/ if you add --archive_logs to command-line options, or have ARCHIVE_EXISTING_LOGS set to True in settings.py, otherwise log files with be cleaned up at the start of the next test run. The test_suite.py collection contains tests that fail on purpose so that you can see how logging works.
cd examples/
pytest test_suite.py --chrome
pytest test_suite.py --firefoxAn easy way to override seleniumbase/config/settings.py is by using a custom settings file.
Here's the command-line option to add to tests: (See examples/custom_settings.py)
--settings_file=custom_settings.py
(Settings include default timeout values, a two-factor auth key, DB credentials, S3 credentials, and other important settings used by tests.)
šµ To pass additional data from the command-line to tests, add --data="ANY STRING".
Inside your tests, you can use self.data to access that.
šµ When running tests with pytest, you'll want a copy of pytest.ini in your root folders. When running tests with pynose, you'll want a copy of setup.cfg in your root folders. These files specify default configuration details for tests. Test folders should also include a blank init.py file to allow your test files to import other files from that folder.
šµ sbase mkdir DIR creates a folder with config files and sample tests:
sbase mkdir ui_testsThat new folder will have these files:
ui_tests/
āāā __init__.py
āāā my_first_test.py
āāā parameterized_test.py
āāā pytest.ini
āāā requirements.txt
āāā setup.cfg
āāā test_demo_site.py
āāā boilerplates/
āāā __init__.py
āāā base_test_case.py
āāā boilerplate_test.py
āāā classic_obj_test.py
āāā page_objects.py
āāā sb_fixture_test.py
āāā samples/
āāā __init__.py
āāā google_objects.py
āāā google_test.py
āāā sb_swag_test.py
āāā swag_labs_test.pyProTipā¢: You can also create a boilerplate folder without any sample tests in it by adding -b or --basic to the sbase mkdir command:
sbase mkdir ui_tests --basicThat new folder will have these files:
ui_tests/
āāā __init__.py
āāā pytest.ini
āāā requirements.txt
āāā setup.cfgOf those files, the pytest.ini config file is the most important, followed by a blank __init__.py file. There's also a setup.cfg file (for pynose). Finally, the requirements.txt file can be used to help you install seleniumbase into your environments (if it's not already installed).
ProTipā¢: Add --gha to include a GitHub Actions .yml file with default settings:
ui_tests/
āāā .github
āāā workflows/
āāā python-package.ymlLet's try an example of a test that fails:
""" test_fail.py """
from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.goto("https://xkcd.com/731/")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=1) # This should failYou can run it from the examples/ folder like this:
pytest test_fail.pyšµ You'll notice that a logs folder, ./latest_logs/, was created to hold information (and screenshots) about the failing test. During test runs, past results get moved to the archived_logs folder if you have ARCHIVE_EXISTING_LOGS set to True in settings.py, or if your run tests with --archive-logs. If you choose not to archive existing logs, they will be deleted and replaced by the logs of the latest test run.
šµ The --dashboard option for pytest generates a SeleniumBase Dashboard located at dashboard.html, which updates automatically as tests run and produce results. Example:
pytest --dashboard --rs --headlessšµ Additionally, you can host your own SeleniumBase Dashboard Server on a port of your choice. Here's an example of that using Python's http.server:
python -m http.server 1948šµ Now you can navigate to http://localhost:1948/dashboard.html in order to view the dashboard as a web app. This requires two different terminal windows: one for running the server, and another for running the tests, which should be run from the same directory. (Use Ctrl+C to stop the http server.)
šµ Here's a full example of what the SeleniumBase Dashboard may look like:
pytest test_suite.py test_image_saving.py --dashboard --rs --headlessā
Using --html=report.html gives you a fancy report of the name specified after your test suite completes.
pytest test_suite.py --html=report.htmlā
When combining pytest html reports with SeleniumBase Dashboard usage, the pie chart from the Dashboard will get added to the html report. Additionally, if you set the html report URL to be the same as the Dashboard URL when also using the dashboard, (example: --dashboard --html=dashboard.html), then the Dashboard will become an advanced html report when all the tests complete.
ā Here's an example of an upgraded html report:
pytest test_suite.py --dashboard --html=report.htmlIf viewing pytest html reports in Jenkins, you may need to configure Jenkins settings for the html to render correctly. This is due to Jenkins CSP changes.
You can also use --junit-xml=report.xml to get an xml report instead. Jenkins can use this file to display better reporting for your tests.
pytest test_suite.py --junit-xml=report.xmlThe --report option gives you a fancy report after your test suite completes.
pynose test_suite.py --report(NOTE: You can add --show-report to immediately display pynose reports after the test suite completes. Only use --show-report when running tests locally because it pauses the test run.)
(The behave_bdd/ folder can be found in the examples/ folder.)
behave behave_bdd/features/ -D dashboard -D headlessYou can also use --junit to get .xml reports for each behave feature. Jenkins can use these files to display better reporting for your tests.
behave behave_bdd/features/ --junit -D rs -D headlessSee: https://allurereport.org/docs/pytest/
SeleniumBase no longer includes allure-pytest as part of installed dependencies. If you want to use it, install it first:
pip install allure-pytestNow your tests can create Allure results files, which can be processed by Allure Reports.
pytest test_suite.py --alluredir=allure_resultsIf you wish to use a proxy server for your browser tests (Chromium or Firefox), you can add --proxy=IP_ADDRESS:PORT as an argument on the command line.
pytest proxy_test.py --proxy=IP_ADDRESS:PORTIf the proxy server that you wish to use requires authentication, you can do the following (Chromium only):
pytest proxy_test.py --proxy=USERNAME:PASSWORD@IP_ADDRESS:PORTSeleniumBase also supports SOCKS4 and SOCKS5 proxies:
pytest proxy_test.py --proxy="socks4://IP_ADDRESS:PORT"
pytest proxy_test.py --proxy="socks5://IP_ADDRESS:PORT"To make things easier, you can add your frequently-used proxies to PROXY_LIST in proxy_list.py, and then use --proxy=KEY_FROM_PROXY_LIST to use the IP_ADDRESS:PORT of that key.
pytest proxy_test.py --proxy=proxy1šµ If you wish to change the User-Agent for your browser tests (Chromium and Firefox only), you can add --agent="USER AGENT STRING" as an argument on the command-line.
pytest user_agent_test.py --agent="Mozilla/5.0 (Nintendo 3DS; U; ; en) Version/1.7412.EU"šµ self.accept_alert() automatically waits for and accepts alert pop-ups. self.dismiss_alert() automatically waits for and dismisses alert pop-ups. On occasion, some methods like self.click(SELECTOR) might dismiss a pop-up on its own because they call JavaScript to make sure that the readyState of the page is complete before advancing. If you're trying to accept a pop-up that got dismissed this way, use this workaround: Call self.find_element(SELECTOR).click() instead, (which will let the pop-up remain on the screen), and then use self.accept_alert() to accept the pop-up (more on that here). If pop-ups are intermittent, wrap code in a try/except block.
šµ Learn about SeleniumBase Interactive Walkthroughs (in the examples/tour_examples/ folder). It's great for prototyping a website onboarding experience.
Here's an example of running tests with some additional features enabled:
pytest [YOUR_TEST_FILE.py] --with-db-reporting --with-s3-loggingšµ Navigating to a web page: (and related commands)
self.goto("https://xkcd.com/378/") # This method opens the specified page.
self.go_back() # This method navigates the browser to the previous page.
self.go_forward() # This method navigates the browser forward in history.
self.refresh_page() # This method reloads the current page.
self.get_current_url() # This method returns the current page URL.
self.get_page_source() # This method returns the current page source.ProTipā¢: You can use the self.get_page_source() method with Python's find() command to parse through HTML to find something specific. (For more advanced parsing, see the BeautifulSoup example.)
source = self.get_page_source()
head_open_tag = source.find('<head>')
head_close_tag = source.find('</head>', head_open_tag)
everything_inside_head = source[head_open_tag+len('<head>'):head_close_tag]šµ Clicking:
To click an element on the page:
self.click("div#my_id")ProTipā¢: In most web browsers, you can right-click on a page and select Inspect Element to see the CSS selector details that you'll need to create your own scripts.
šµ Typing Text:
self.type(selector, text) # updates the text from the specified element with the specified value. An exception is raised if the element is missing or if the text field is not editable. Example:
self.type("input#id_value", "2012")You can also use self.add_text() or the WebDriver .send_keys() command, but those won't clear the text box first if there's already text inside.
šµ Getting the text from an element on a page:
text = self.get_text("header h2")šµ Getting the attribute value from an element on a page:
attribute = self.get_attribute("#comic img", "title")šµ Asserting existence of an element on a page within some number of seconds:
self.wait_for_element_present("div.my_class", timeout=10)(NOTE: You can also use: self.assert_element_present(ELEMENT))
šµ Asserting visibility of an element on a page within some number of seconds:
self.wait_for_element_visible("a.my_class", timeout=5)(NOTE: The short versions of that are self.find_element(ELEMENT) and self.assert_element(ELEMENT). The find_element() version returns the element.)
Since the line above returns the element, you can combine that with .click() as shown below:
self.find_element("a.my_class", timeout=5).click()
# But you're better off using the following statement, which does the same thing:
self.click("a.my_class") # DO IT THIS WAY!ProTipā¢: You can use dots to signify class names (Ex: div.class_name) as a simplified version of div[class="class_name"] within a CSS selector.
You can also use *= to search for any partial value in a CSS selector as shown below:
self.click('a[name*="partial_name"]')šµ Asserting visibility of text inside an element on a page within some number of seconds:
self.assert_text("Make it so!", "div#trek div.picard div.quotes")
self.assert_text("Tea. Earl Grey. Hot.", "div#trek div.picard div.quotes", timeout=3)(NOTE: self.find_text(TEXT, ELEMENT) and self.wait_for_text(TEXT, ELEMENT) also do this. For backwards compatibility, older method names were kept, but the default timeout may be different.)
šµ Asserting Anything:
self.assert_true(var1 == var2)
self.assert_false(var1 == var2)
self.assert_equal(var1, var2)šµ Useful Conditional Statements: (with creative examples)
ā is_element_visible(selector): (visible on the page)
if self.is_element_visible('div#warning'):
print("Red Alert: Something bad might be happening!")ā is_element_present(selector): (present in the HTML)
if self.is_element_present('div#top_secret img.tracking_cookie'):
self.contact_cookie_monster() # Not a real SeleniumBase method
else:
current_url = self.get_current_url()
self.contact_the_nsa(url=current_url, message="Dark Zone Found") # Not a real SeleniumBase methoddef is_there_a_cloaked_klingon_ship_on_this_page():
if self.is_element_present("div.ships div.klingon"):
return not self.is_element_visible("div.ships div.klingon")
return Falseā is_text_visible(text, selector): (text visible on element)
if self.is_text_visible("You Shall Not Pass!", "h1"):
self.goto("https://www.youtube.com/watch?v=3xYXUeSmb-Y")def get_mirror_universe_captain_picard_superbowl_ad(superbowl_year):
selector = "div.superbowl_%s div.commercials div.transcript div.picard" % superbowl_year
if self.is_text_visible("Yes, it was I who summoned you all here.", selector):
return "Picard Paramount+ Superbowl Ad 2020"
elif self.is_text_visible("Commander, signal the following: Our Network is Secure!"):
return "Picard Mirror Universe iboss Superbowl Ad 2018"
elif self.is_text_visible("For the Love of Marketing and Earl Grey Tea!", selector):
return "Picard Mirror Universe HubSpot Superbowl Ad 2015"
elif self.is_text_visible("Delivery Drones... Engage", selector):
return "Picard Mirror Universe Amazon Superbowl Ad 2015"
elif self.is_text_visible("Bing it on Screen!", selector):
return "Picard Mirror Universe Microsoft Superbowl Ad 2015"
elif self.is_text_visible("OK Glass, Make it So!", selector):
return "Picard Mirror Universe Google Superbowl Ad 2015"
elif self.is_text_visible("Number One, I've Never Seen Anything Like It.", selector):
return "Picard Mirror Universe Tesla Superbowl Ad 2015"
elif self.is_text_visible("Let us make sure history never forgets the name ... Facebook", selector):
return "Picard Mirror Universe Facebook Superbowl Ad 2015"
elif self.is_text_visible("""With the first link, the chain is forged.
The first speech censored, the first thought forbidden,
the first freedom denied, chains us all irrevocably.""", selector):
return "Picard Mirror Universe Wikimedia Superbowl Ad 2015"
else:
raise Exception("Reports of my assimilation are greatly exaggerated.")ā is_link_text_visible(link_text):
if self.is_link_text_visible("Stop! Hammer time!"):
self.click_link("Stop! Hammer time!")self.switch_to_window(1) # This switches to the new tab (0 is the first one)šµ iframes follow the same principle as new windows: You must first switch to the iframe if you want to perform actions in there:
self.switch_to_frame("iframe")
# ... Now perform actions inside the iframe
self.switch_to_parent_frame() # Exit the current iframeTo exit from multiple iframes, use self.switch_to_default_content(). (If inside a single iframe, this has the same effect as self.switch_to_parent_frame().)
self.switch_to_frame('iframe[name="frame1"]')
self.switch_to_frame('iframe[name="frame2"]')
# ... Now perform actions inside the inner iframe
self.switch_to_default_content() # Back to the main pagešµ You can also use a context manager to act inside iframes:
with self.frame_switch("iframe"):
# ... Now perform actions while inside the code block
# You have left the iframeThis also works with nested iframes:
with self.frame_switch('iframe[name="frame1"]'):
with self.frame_switch('iframe[name="frame2"]'):
# ... Now perform actions while inside the code block
# You are now back inside the first iframe
# You have left all the iframes<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>šµ It's OK if you want to use jQuery on a page that doesn't have it loaded yet. To do so, run the following command first:
self.activate_jquery()self.execute_script("jQuery, window.scrollTo(0, 600)") # Scrolling the page
self.execute_script("jQuery('#annoying-widget').hide()") # Hiding elements on a page
self.execute_script("jQuery('#hidden-widget').show(0)") # Showing hidden elements on a page
self.execute_script("jQuery('#annoying-button a').remove()") # Removing elements on a page
self.execute_script("jQuery('%s').mouseover()" % (mouse_over_item)) # Mouse-over elements on a page
self.execute_script("jQuery('input#the_id').val('my_text')") # Fast text input on a page
self.execute_script("jQuery('div#dropdown a.link').click()") # Click elements on a page
self.execute_script("return jQuery('div#amazing')[0].text") # Returns the css "text" of the element given
self.execute_script("return jQuery('textarea')[2].value") # Returns the css "value" of the 3rd textarea element on the page(Most of the above commands can be done directly with built-in SeleniumBase methods.)
ā Some websites have a restrictive Content Security Policy to prevent users from loading jQuery and other external libraries onto their websites. If you need to use jQuery or another JS library on those websites, add --disable-csp as a pytest command-line option to load a Chromium extension that bypasses the CSP.
start_page = "https://xkcd.com/465/"
destination_page = "https://github.com/seleniumbase/SeleniumBase"
self.goto(start_page)
referral_link = '''<a class='analytics test' href='%s'>Free-Referral Button!</a>''' % destination_page
self.execute_script('''document.body.innerHTML = \"%s\"''' % referral_link)
self.click("a.analytics") # Clicks the generated button(Due to popular demand, this traffic generation example has been included in SeleniumBase with the self.generate_referral(start_page, end_page) and the self.generate_traffic(start_page, end_page, loops) methods.)
from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)
class DeferredAssertTests(BaseCase):
def test_deferred_asserts(self):
self.goto("https://xkcd.com/993/")
self.wait_for_element("#comic")
self.deferred_assert_element('img[alt="Brand Identity"]')
self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail
self.deferred_assert_element("#comicmap")
self.deferred_assert_text("Fake Item", "ul.comicNav") # Will Fail
self.deferred_assert_text("Random", "ul.comicNav")
self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail
self.deferred_assert_exact_text("Brand Identity", "#ctitle")
self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail
self.process_deferred_asserts()deferred_assert_element() and deferred_assert_text() will save any exceptions that would be raised. To flush out all the failed deferred asserts into a single exception, make sure to call self.process_deferred_asserts() at the end of your test method. If your test hits multiple pages, you can call self.process_deferred_asserts() before navigating to a new page so that the screenshot from your log files matches the URL where the deferred asserts were made.
self.driver.delete_all_cookies()
capabilities = self.driver.capabilities
self.driver.find_elements("partial link text", "GitHub")(In general, you'll want to use the SeleniumBase versions of methods when available.)
pytest --reruns=1 --reruns-delay=1"Catch bugs in QA before deploying code to Production!"
Available Tools
24 toolsassert_conditionAssert ConditionARead-onlyIdempotent
Verify a browser condition and report failure as an error.
Use this tool when an expected page state must be explicitly verified. It is a read-only verification operation: it does not click, type, navigate, scroll, or otherwise intentionally modify the page.
Element and text assertions may block while SeleniumBase waits for the
condition, up to timeout seconds. Title and URL assertions are checked
immediately and ignore timeout. A failed assertion or timeout is
handled by handle_sb_errors and returned as a descriptive tool error;
it is not reported as a successful result.
Unlike check_if_condition, this tool does not merely return whether a condition is true: a failed expectation is an error. Unlike wait_for_condition, its purpose is to verify an expectation, not merely synchronize with a changing page.
Args: check: - "element_present": Verify that the selector identifies a present element. - "element_visible": Verify that the selector identifies a visible element. - "text_visible": Verify that expected text is visible within selector, or within the whole HTML document if selector is omitted. - "title": Verify the exact current page title immediately. - "url": Verify the exact current URL immediately. - "url_contains": Verify that the current URL contains expected immediately.
selector: CSS or SeleniumBase selector for element and text checks.
Required for element checks; optional for text_visible.
expected: Expected text, title, or URL value. Required for
text_visible, title, url, and url_contains.
exact: For text_visible only, require an exact text match instead
of a substring match.
timeout: Maximum seconds to wait for element/text assertions.
Must be >= 0. Ignored for title and URL assertions.Returns: A confirmation message when the assertion passes. If the assertion fails or times out, the error handler returns the resulting error instead of a success message.
Tool selection: - Inspect a condition without failing -> check_if_condition. - Wait for a condition to become true -> wait_for_condition. - Verify that an expected condition is true -> assert_condition.
Inputs: check, exact, timeout, expected, +1 more. Returns: result
check_if_conditionCheck ConditionARead-onlyIdempotent
Check the current state of an element or text without waiting for the condition to become true.
Use this tool when you need an immediate boolean observation of the current page state. Use wait_for_condition when the condition may become true later and the workflow should wait for it. Use assert_condition when the condition is an expected requirement and failure should be treated as an assertion error.
Args:
check:
The element state to inspect when text is not provided:
- "present": Return True when at least one matching element exists.
- "visible": Return True when the matching element is visible.
check is ignored when text is provided.
selector:
CSS selector or SeleniumBase selector identifying the element.
text:
Optional text to check for visibility within `selector`. When
provided, this takes precedence over `check`; the tool checks text
visibility instead of element presence or visibility. Use this when
the question is "Is this text currently visible?" rather than
whether the element itself is present or visible.Returns: True or False indicating whether the requested condition is currently satisfied. Missing elements return False rather than raising an exception. If there's an error, returns a string with error details.
Tool selection: - Immediate boolean observation -> use check_if_condition. - Wait for a state/content transition -> use wait_for_condition. - Verify an expected condition -> use assert_condition. - Need element details of matching elements -> use find_elements. - Need to read page or element content -> use get_content.
Notes: This tool does not intentionally wait for elements or text to appear. It is intended for checking the current state only. If page timing or asynchronous loading matters, use wait_for_condition instead.
Inputs: text, check, selector. Returns: result
click_elementClick ElementA
Click element(s) matching a CSS, XPath, or supported text selector.
Use this tool for normal clicks, clicking a specific matching occurrence, clicking all visible matches, conditional clicks, or clicks scoped to a parent element.
Selection behavior and priority:
nth is 1-based and takes precedence over every other click mode.
Otherwise, all_matches=True clicks every currently visible match.
Otherwise, only_if_visible=True clicks only if a match is visible.
Otherwise, parent_selector scopes the click to a nested element.
If none of the above are set, then a regular click is performed.
Args:
selector: CSS selector, XPath selector, or supported SeleniumBase
text-matching selector. Text-matching selectors such as
a:contains("Sign in") are supported only for single-element
clicks; do not use them with all_matches=True.
nth: 1-based occurrence to click when multiple elements match.
Must be >= 1 if provided. Takes precedence over `all_matches`,
`only_if_visible`, and `parent_selector`.
all_matches: If True, click every currently visible matching element
in order of appearance. Ignored when `nth` is provided. Use only
when multiple clicks are intentionally desired, such as for
clicking all the checkboxes in a section of a webpage.
If any of the click actions induces page navigation, then
subsequent clicks are cancelled without any exceptions raised.
only_if_visible: If True, click only when the target is already
visible; do not wait for it to become visible.
parent_selector: CSS/XPath selector for the parent/container in which
to find `selector`. Used only for the nested-click mode.
Can be used to click an element inside a parent iframe.
timeout: Maximum seconds to wait for a normal click operation.
Default: 5. Not used by conditional or bulk click modes.
scroll: If True, scroll the target into view before a normal or
indexed click. Default: True.Examples:
- Click the first button: click_element("button")
- Click the 2nd button: click_element("button", nth=2)
- Click all checkboxes:
click_element('input[type="checkbox"]', all_matches=True)
- Click the first visible link:
click_element("a", only_if_visible=True)
- Click the first button that's inside the first iframe:
click_element("button", parent_selector="iframe")
Error behavior: With the exception of using 'only_if_visible=True', if there's no matching element found within the timeout, then @handle_sb_errors returns details from the exception raised.
When not to use: - Do not use this tool if you need to hover an element first before clicking; use hover_action with action="hover_and_click" instead.
Inputs: selector (required), nth, scroll, timeout, +3 more. Returns: result
close_browserClose BrowserAIdempotent
Close the active browser session and release browser resources.
Call this when the browser automation workflow is finished. Closing the session ends the persistent browser state, including its open tabs, cookies, navigation history, and page state. If browser automation is needed afterward, start a new session with start_browser.
This operation is safe to call when no browser session is active.
Inputs: no named parameters. Returns: result
find_elementsFind ElementsARead-onlyIdempotent
Find matching elements and return structured element information.
Use this tool when you need to discover how many elements match a selector, inspect their text/tag names, or inspect the HTML of multiple matches.
This tool converts matching elements into ordinary serializable dictionaries. It does not return live SeleniumBase element objects.
Args:
selector: A CSS selector, or an XPath selector that SeleniumBase can
convert to CSS. In sb.find_elements, SeleniumBase automatically
attempts to convert XPath to CSS. Some XPath expressions, such
as those using contains(...), cannot be converted to CSS and
therefore aren't supported by this tool.
timeout: Maximum number of seconds to wait for at least one matching
element to appear. If the selector is an XPath selector that
cannot be converted into a valid CSS selector, then the wait
might be less than the timeout.
include_html: If True, include each matching element's outer HTML.
If False, return only tag name and text.Returns: A dictionary containing: - count: Number of matching elements found. - matches: A list of element dictionaries containing tag_name and text, plus html when include_html=True. If there's an error during search, then "error" is added into the returned dictionary with error details.
Tool selection: - Need structured information about matching elements -> use find_elements. - Need the visible text/HTML of a page or a single element -> use get_content. - Need to click one of several matches -> use click_element with nth. - Need to know whether an element is present/visible -> use check_if_condition.
Notes: Element handles cannot be persisted across MCP calls. If you find elements and then need to act on one, resolve it again with the appropriate interaction tool.
For uncaught errors, @handle_sb_errors returns strings.
Inputs: selector (required), timeout, include_html. Returns: result
focus_elementFocus ElementA
Scroll to, focus, or highlight an element.
This tool does not click, type, select, hover, or otherwise activate the
element. Use click_element, type_text, or hover_action for those
operations.
Args: selector: CSS selector or SeleniumBase selector identifying the target.
action:
- "scroll_to_element": Scroll the element into the viewport.
- "focus": Move keyboard focus to the element.
- "highlight": Temporarily highlight the element for debugging or
demonstration by changing the border color. May affect timing
and/or reduce stealth.
timeout: Maximum seconds to wait for the target element. Default: 5.If there's no matching element found within the timeout, then @handle_sb_errors returns details from the exception raised.
Inputs: selector (required), action, timeout. Returns: result
get_attributesGet AttributesARead-onlyIdempotent
Get a specific HTML attribute (or all attributes) from the selected element. Examples of possible attributes include href, src, value, class, id, name, type, aria-label, etc.
Args: selector: CSS selector or SeleniumBase-supported XPath selector. If multiple elements match, then only the first one is used.
attribute: Specific HTML attribute to retrieve. When omitted, returns
all HTML attributes of the matching element as a dictionary.
timeout: Maximum seconds to wait for the target element. Default: 5.Tool selection: - Need one or more HTML attribute values from a specific element -> use this tool. - Need to discover multiple matching elements or inspect their text -> use 'find_elements'. - Need visible text or HTML content -> use 'get_content'. - Need to check element presence/visibility -> use 'check_if_condition'.
If there's no matching element found within the timeout, then @handle_sb_errors returns details from the exception raised.
Inputs: selector (required), timeout, attribute. Returns: result
get_contentGet ContentARead-onlyIdempotent
Get visible text, HTML, or discovered URLs from the selected element.
Args: selector: CSS selector or SeleniumBase-supported XPath selector. Default: "body".
output_format:
- "text": Return visible text from the selected element.
- "html": Return HTML from the selected element.
- "urls": Return URLs discovered by SeleniumBase within the
selected element. Returned URLs are normalized to full URLs
with their protocol prefixes.
timeout: Maximum seconds to wait for the target element. Default: 5.Tool selection: - Need URL, title, origin, or User-Agent -> use get_page_info. - Need visible text, html, or URLs on a page -> use get_content. - Need structured information about matching elements -> use find_elements. - Need to check element presence/visibility -> use check_if_condition. - Need to wait for content to appear -> use wait_for_condition.
If there's no matching element found within the timeout, then @handle_sb_errors returns details from the exception raised.
Inputs: timeout, selector, output_format. Returns: result
get_page_infoGet Page InfoARead-onlyIdempotent
Get current browser session and page metadata.
Use this as the primary tool for determining where the browser currently is after navigation, clicks, form submissions, redirects, reloads, or tab switches.
This is a read-only metadata operation: It does not inspect arbitrary page content, find elements, check visibility, wait for conditions, or assert expected values.
Returns: A dictionary containing: - running: True when browser metadata was successfully retrieved. False when no session is available or metadata retrieval failed. - url: The complete current page URL, including path and query string. - title: The current document title. - origin: The current page origin (scheme, host, and port). - user_agent: The browser's current User-Agent string.
Tool selection: - Need URL, title, origin, or User-Agent -> use get_page_info. - Need visible page text or HTML -> use get_content. - Need information about matching elements -> use find_elements. - Need an immediate state check -> use check_if_condition. - Need to wait for a condition -> use wait_for_condition. - Need to verify an expected condition -> use assert_condition.
Unlike a dedicated browser-status tool, get_page_info is the single source of browser/page metadata. If no browser session is active, it returns {"running": False} instead of attempting to access a page.
This operation does not navigate, reload, click, type, or otherwise modify the current page.
Inputs: no named parameters. Returns: object
hover_actionHover / Click / DragA
Hover over an element, optionally click another, or drag-and-drop.
Use this tool for hover interactions, hover-triggered menus, and drag-and-drop operations.
Args: selector: The primary element selector. For action="hover", this is the element to hover over. For action="hover_and_click", this is the element to hover over before clicking 'secondary_selector'. For action="drag_and_drop", this is the draggable source element.
secondary_selector:
The secondary element selector.
Required for action="hover_and_click", where it identifies
the element to click after hovering 'selector'.
Required for action="drag_and_drop", where it identifies the
destination/drop target.
Not used for action="hover".
action:
- "hover": Hover over 'selector' only.
- "hover_and_click": Hover over 'selector', then click
'secondary_selector' after a short moment has passed.
- "drag_and_drop": Drag 'selector' and drop it onto
'secondary_selector'.
timeout: Maximum seconds to wait for 'selector'.
For drag_and_drop, the same timeout applies to secondary_selector.
For hover_and_click, SeleniumBase uses its own short wait for
secondary_selector; this parameter does not extend that secondary
wait.Returns: A confirmation message describing the performed operation's result.
Error behavior: If a required element cannot be found or interacted with within the applicable wait period, or if an error occurs during the action, the resulting exception message is returned through @handle_sb_errors. Failing actions such as failed hover_and_click will raise exceptions.
When not to use: - Do not use this tool to click if you don't need to hover an element before clicking another; use 'click' instead.
Inputs: selector (required), action, timeout, secondary_selector. Returns: result
manage_cookiesManage CookiesAIdempotent
Manage cookies for the current browser session.
Use this tool to inspect, clear, save, or restore browser cookies. Cookie management is useful for inspecting session state, preserving login sessions between browser runs, restoring previously saved sessions, or resetting website state during testing.
Args: action: - "get_all": Return all cookies currently available to the browser, including attributes such as name, value, domain, path, expiry, and security flags. - "clear": Delete all cookies from the current browser session. - "save": Save current cookies to filename. The file may be created or overwritten. - "load": Load cookies from filename into the current browser session.
filename: The sanitized filesystem path used by save/load.
Ignored for get_all and clear.Returns: "get_all": Current browser cookies. "clear": Confirmation that cookies were cleared. "save": Confirmation containing the destination filename. "load": Confirmation containing the source filename.
Security: Cookie data can contain authentication credentials, session identifiers, and other private information. Only inspect, save, load, or share cookies when explicitly authorized.
The save action can overwrite existing files.Notes: Loading saved cookies does not guarantee restoration of a login. Cookies may be expired, invalidated, domain/path restricted, or dependent on other browser state. Navigate to the relevant site when necessary so the browser has the appropriate origin for the cookies.
Inputs: action, filename.
manage_historyManage HistoryA
Manage or inspect the current browser tab's navigation history.
Use "back", "forward", or "reload" actions for history navigation. Use "list" to inspect history. (This one is read-only.) Use 'open_url' for navigation to an arbitrary URL.
Args: action: - "back": Go to the previous history entry, if available. - "forward": Go to the next history entry, if available. - "reload": Reload the current page while ignoring the cache. - "list": Return the current history position and entries.
Navigation actions can trigger page loads or redirects. Use 'get_page_info' afterward to verify the resulting URL or title.
Inputs: action. Returns: result
manage_storageManage StorageA
Get or set a key in localStorage or sessionStorage.
Use this tool when the browser workflow needs to inspect or modify JavaScript Web Storage belonging to the current page origin.
Tool selection: - Need localStorage/sessionStorage -> use this tool. - Need cookies or authentication cookies -> use manage_cookies. - Need arbitrary JavaScript or storage operations not covered here -> use run_javascript. - Need visible page content or HTML -> use get_content. - Need an element's HTML attributes -> use get_attributes.
When not to use: - Do not use this tool for HTTP cookies; use manage_cookies instead. - Do not use this tool for arbitrary page JavaScript; use run_javascript when a higher-level tool is insufficient. - Do not use this tool to inspect values from another origin; storage is scoped to the current page origin.
Args: key: Storage key to read or modify.
value: Value to store when action="set". Required for set.
storage: "local" for localStorage or "session" for sessionStorage.
action: "get" to read the key or "set" to write the key.Returns: The stored value for get, or a confirmation message for set.
Security: Web storage can contain authentication tokens, session identifiers, and other sensitive application state. Only use this tool with trusted sites and authorized MCP clients.
Notes: Storage belongs to the current page origin. Values from one website are not generally available to another origin.
Inputs: key (required), value, action, storage.
manage_tabsManage TabsA
Manage browser tabs, including opening new ones.
Use this for listing, opening, switching, or closing tabs.
Use open_url and manage_history for navigation within the active tab.
Args:
action:
- "list_tabs": Return each tab's index, URL, and title.
Use this to find the tab_index for "switch_to_tab".
- "open_new_tab": Open a new tab, optionally navigating to url.
- "switch_to_tab": Switch to the tab at tab_index from "list_tabs".
- "switch_to_newest_tab": Switch to the newest tab.
- "close_active_tab": Close the active tab. This action must be
followed by a 'manage_tabs' action that switches to a new
tab, such as "switch_to_tab" or "switch_to_newest_tab".
url: URL for "open_new_tab". If not provided, "about:blank" is used.
tab_index: Tab index from "list_tabs" that is only used for the
"switch_to_tab" action.)
switch_to: If using "open_new_tab", switch to the new tab when True.Notes: Tab indexes are session-relative and may change after tabs are opened or closed. Use "list_tabs" to get current indexes before switching by index.
Error behavior: If there's an error during any of the tab actions, then @handle_sb_errors will propagate the exception as an error message.
Inputs: url, action, switch_to, tab_index. Returns: result
manage_windowManage WindowAIdempotent
Get or change browser window geometry or state.
Args: action: - "get_rect": Return the current window position and size. - "set_rect": Set x, y, width, and height. All four are required. - "maximize": Maximize the browser window. - "minimize": Minimize the browser window.
x: Horizontal screen position for "set_rect".
y: Vertical screen position for "set_rect".
width: Window width for "set_rect".
height: Window height for "set_rect".Notes:
Use this tool for browser-window geometry and state.
Use manage_tabs for switching between browser tabs.
Inputs: x, y, width, action, +1 more. Returns: result
open_urlOpen URLA
Navigate the current browser tab to the URL provided.
Use this when the browser needs to visit a new URL rather than move through its existing back/forward history.
If the URL does not include a protocol such as "https://", SeleniumBase automatically prefixes "https://" before navigation. For example, "seleniumbase.io" becomes "https://seleniumbase.io".
Navigation waits for the browser's navigation operation to complete before returning. Dynamic content may still be loading; use wait_for_condition when synchronization is required. If there's an error, that gets propagated through @handle_sb_errors.
Args: url: The destination URL. May be a complete URL such as "https://example.com", or a hostname such as "example.com".
Returns: A confirmation message containing the requested URL if successful.
Tool selection: - Navigate to a new URL -> use open_url. - Return to the previous page -> use manage_history(action="back"). - Go forward in history -> use manage_history(action="forward"). - Refresh the current page -> use manage_history(action="reload").
Inputs: url (required). Returns: result
run_javascriptRun JavaScriptA
Evaluate a JavaScript expression in the current page context.
Use this only when the required browser operation cannot be accomplished through the higher-level SeleniumBase tools.
The expression is evaluated through Chrome DevTools Protocol Runtime.evaluate in the currently active page. It executes with access to the page's JavaScript context, including DOM APIs, browser storage, and other same-origin page resources available to JavaScript.
Tool selection: - Prefer click_element, type_text, select_option, hover_action, focus_element, scroll_page, and other higher-level tools for normal browser interactions. - Prefer get_content, get_attributes, and find_elements for reading page content or element information. - Prefer manage_storage for ordinary localStorage/sessionStorage reads and writes. - Prefer manage_cookies for browser cookie operations. - Use this tool when a required operation needs arbitrary JavaScript that the higher-level tools do not expose.
Args: expression: A JavaScript expression or executable JavaScript code evaluated in the current page. It may reference standard browser globals such as document and window and may use DOM APIs.
Examples:
- "document.title"
- "document.querySelector('button')?.textContent"
- "localStorage.getItem('theme')"
- "document.body.classList.contains('dark')"
- "document.querySelector('#slider').value = '50'"
The expression should produce a value when a result is needed.
JavaScript that returns a Promise is supported and its resolved
value is returned.Returns: The JavaScript evaluation result when it can be serialized and returned across the MCP boundary. Primitive values, arrays, plain objects, and null are generally suitable return values. DOM objects, functions, symbols, and other non-serializable JavaScript values may not be returned directly; extract the needed property or convert the value to a serializable form first.
Security: This provides unrestricted JavaScript execution in the current browser page. It can read or modify page data and interact with the page in ways that bypass the higher-level tool abstractions. Only expose this MCP server to trusted clients.
Inputs: expression (required).
save_pageSave PageA
Save the current browser page to a local filesystem file.
Use this tool when the browser workflow needs a persistent file artifact from the current page: a PNG screenshot, the current page source as HTML, or a PDF representation of the current page.
A browser session must already be running. This tool operates on the currently active browser tab and does not navigate, click, type, or otherwise modify the webpage.
Args: format: - "screenshot": Save a PNG screenshot of the current page. - "html": Save the current page source as an HTML file. - "pdf": Save the current page as a PDF.
filename:
Optional output filename. If omitted, defaults to:
- "screenshot.png" for format="screenshot"
- "page_source.html" for format="html"
- "page.pdf" for format="pdf"
folder:
Optional destination folder passed to SeleniumBase.
If omitted, SeleniumBase uses its default output location.Side effects and filesystem behavior: This tool writes a file to the filesystem and may overwrite an existing file with the same output name. Only use trusted and authorized filesystem paths. The MCP process must have permission to write to the requested destination.
The tool does not upload, publish, or transmit the saved file by
itself. The resulting file remains in the filesystem available to
the MCP server process.Error behavior: If the browser session is not running, the tool returns a lifecycle error. Filesystem, browser, or SeleniumBase failures are converted into descriptive MCP error results by the server's error handler.
When not to use: - Do not use this tool merely to read page text or HTML; use get_content instead. - Do not use this tool when you only need page metadata such as the URL or title; use get_page_info instead. - Do not use this tool to manipulate the page; use the appropriate interaction tool such as click_element, type_text, or select_option.
Returns: A confirmation message containing the requested output format and filename after the save operation succeeds.
Inputs: folder, format, filename. Returns: result
scroll_pageScroll PageA
Scroll the current page vertically.
Args: direction: - "up": Scroll upward by amount percent of the window height. - "down": Scroll downward by amount percent of the window height. - "top": Scroll directly to the top; amount is ignored. - "bottom": Scroll directly to the bottom; amount is ignored.
amount: Percentage of the current viewport height used for relative
up/down scrolling. For example, amount=25 scrolls approximately
one quarter of the viewport height.Notes:
Values greater than 100 for amount are allowed.
For example, 200 means approximately two viewport heights.
Tool selection: - Need to reveal a specific element -> use 'focus_element' with action="scroll_to_element". - Need to scroll the page by a relative amount -> use 'scroll_page'.
Inputs: amount, direction. Returns: result
select_optionSelect OptionA
Select an option from an HTML dropdown.
Changing a dropdown selection can trigger additional events on a page.
Args: dropdown_selector: CSS selector identifying the element.
value: The option's visible text, its HTML value attribute, or its
0-based index, depending on by.
by:
- "text": Match the option's visible text.
- "value": Match the option's HTML value attribute.
- "index": Match the option's 0-based position. Both integer and
numeric-string values are accepted.Raises: An error when the dropdown or requested option cannot be found.
This tool is for native elements. For custom JavaScript dropdowns made from div/button/list elements, use click_element or other element-interaction tools instead.
Inputs: value (required), dropdown_selector (required), by. Returns: result
solve_captchaSolve CAPTCHAA
Attempts a SeleniumBase CDP interaction (click or drag/drop) to solve detectable CAPTCHAs on the current page.
Supported CAPTCHAs:
CF Turnstile, reCAPTCHA, hCaptcha, DataDome Slider, FriendlyCaptcha
Tool workflow:
Inspect page structure (e.g., via
get_content) to verify that a CAPTCHA is present.Call
solve_captchaif there's a CAPTCHA. (No-op if no CAPTCHA.)Verify success via
get_page_info,get_content, ormanage_cookies.
Notes: This tool does not guarantee that the CAPTCHA gets solved. A successful attempt may result in changes to page state and cookies.
Tool Selection:
Use
solve_captchaspecifically for automated CAPTCHA widget interactions.Use
click_elementfor standard visible elements.Use
hover_action(action="hover_and_click") to reveal and click targets.
Returns: A confirmation message indicating that the attempt was initiated.
Inputs: no named parameters. Returns: result
start_browserStart BrowserAIdempotent
Launch a persistent SeleniumBase Pure CDP Mode browser session.
Call this before using browser interaction tools such as open_url, get_content, click_element, type_text, or find_elements. The same browser session remains active across subsequent MCP tool calls until close_browser is called or the server process exits.
Pure CDP Mode controls the browser through the Chrome DevTools Protocol (CDP), not WebDriver.
Args: url: Optional URL to navigate to during browser startup. When provided, the tool waits for the browser launch/navigation operation to complete before returning. If omitted, the browser starts without navigating to a specified URL.
headless: Controls whether the browser runs without a visible window.
True forces headless mode; False forces headed mode. If None, this
tool defaults to headless on Linux and headed on Windows/macOS.
use_chromium: Use Chromium instead of Google Chrome. This is useful
when Google Chrome is not installed. SeleniumBase can manage the
Chromium browser when this option is enabled.
browser_executable_path: Optional path to the browser executable.
Use this when the desired browser is installed at a non-standard
location. Mutually exclusive with use_chromium.
incognito: Launch Chrome/Chromium in incognito mode.
guest: Launch Chrome/Chromium in guest mode.
Do not combine this with incognito=True.
ad_block: Enable SeleniumBase's basic ad-blocking functionality.
proxy: Optional proxy server.
Examples include "SERVER:PORT" or "USER:PASS@SERVER:PORT".Returns: A confirmation message when the browser starts successfully, or a descriptive error if the browser startup fails.
Startup behavior: If the initial launch fails, the tool automatically retries once.
Lifecycle: Call start_browser once at the beginning of a browser automation workflow. Reusing the existing session preserves cookies, tabs, navigation history, localStorage/sessionStorage, and other browser state between tool calls. Call close_browser when finished. If a browser session is already running, this tool does not launch another browser and instead returns a message indicating that the existing session is active.
Environment requirements: The MCP runtime must have a compatible Chrome or Chromium browser available. If the browser executable cannot be discovered, use use_chromium=True or provide browser_executable_path explicitly.
Inputs: url, guest, proxy, ad_block, +4 more. Returns: result
type_textType TextA
Enter, append, directly set, or clear a value on a page element.
Use this tool to modify text/value fields such as inputs, textareas, contenteditable elements, and supported input sliders. It changes the target element's value or content; it does not submit a form or click other elements.
Choose the mode based on the desired interaction:
"fill_input": Normal user-like entry; clears the existing value first.
"append": Preserves the existing value and adds text via keystrokes.
"fast_type": Clears the existing value and types without typing pauses.
"set_value": Sets the value directly without simulating key events; prefer this for fast programmatic value changes when keyboard events are not required.
"clear_only": Clears the existing value;
textis ignored.
The tool waits up to timeout seconds for the target element. If the
target cannot be used successfully, the underlying SeleniumBase error is
handled by handle_sb_errors rather than returning a success message.
Args: selector: CSS or SeleniumBase selector identifying the target element.
text: Text/value to enter or set. Ignored for "clear_only".
mode: Interaction mode. See the mode descriptions above.
timeout: Maximum seconds to wait for the target element.
Must be appropriate for the page's expected load/interaction time.Returns: A confirmation message after the operation succeeds; otherwise the error handler returns the resulting failure.
Notes:
Including "\n" in your text (except in "set_value" mode) will
simulate pressing the "Enter" key, which is useful for submitting
forms or triggering search inputs without needing a separate click.
Tool selection: - Need to update text that appears in a text field -> use this tool. - Need to update the value of a element -> use select_option.
Inputs: selector (required), mode, text, timeout. Returns: result
wait_for_conditionWait For ConditionARead-onlyIdempotent
Wait for a page condition or for a specified duration.
Use this for synchronization when a dynamic page may need time to reach a condition before the next automation step. The tool blocks until the condition is met or the timeout expires. It does not intentionally scroll, click, or otherwise modify the page while waiting.
Use check_if_condition to inspect the current state without waiting. Use assert_condition to verify an expected condition rather than synchronize with a changing page.
When the condition is not reached before timeout, the underlying
SeleniumBase wait failure is handled by the tool's error handler rather
than returning a success confirmation.
If state="seconds_passed", selector and text are ignored and the
tool blocks for the full timeout seconds.
If text is supplied, present/visible wait for the text to appear,
while absent/not_visible wait for the text to disappear.
If no selector is supplied, text is searched within the page body.
Args:
state:
- "present": Wait until the matching element exists.
- "visible": Wait until the matching element is visible.
- "not_visible": Wait until the matching element is not visible.
- "absent": Wait until the matching element no longer exists.
- "seconds_passed": Wait for the full timeout duration.
selector: CSS or SeleniumBase selector for the element.
Required unless `text` is supplied or `state="seconds_passed"`.
text: Optional text to wait for or wait to disappear.
With text, `present` and `visible` are equivalent,
as are `absent` and `not_visible`.
timeout: Maximum seconds to wait for the condition;
for `seconds_passed`, the exact duration to wait. Must be >= 0.Returns: A success message when the requested condition is reached. If the condition times out or the underlying wait fails, the tool returns the error produced by its error handler.
Tool selection: - Inspect current state immediately -> check_if_condition. - Wait for a state change -> wait_for_condition. - Verify an expectation -> assert_condition.
Inputs: text, state, timeout, selector. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogā¦
TDQS
Scored across 24 tools
Each tool targets a clearly distinct browser automation concern, and the condition-related tools (check_if_condition, wait_for_condition, assert_condition) are explicitly differentiated by their semantics. Read-style tools like get_content, find_elements, and get_attributes also have clear boundaries despite touching similar page data.
Tool names overwhelmingly follow a consistent snake_case imperative verb_noun pattern, with useful groups like get_*, manage_*, and *_condition. Minor deviations like hover_action and check_if_condition are still readable and do not create real confusion.
At 24 tools, the server is on the heavier side, but the count is justified by the breadth of browser automation: lifecycle, navigation, content extraction, interaction, state checking, tabs, windows, storage, cookies, and JavaScript execution. It is slightly over the ideal compact range but not bloated.
The surface covers the core browser automation lifecycle well: launch/close, navigation, reading content, interacting with elements, waiting/asserting, managing tabs/windows/cookies/storage, and saving page artifacts. Notable gaps like file upload handling and native alert/dialog interaction are absent but can often be worked around via run_javascript or other primitives.
Maintenance
Related MCP Connectors
Crawl, scrape, search the web, and automate browsers at scale with anti-bot bypass.
Undetectable cloud browser sessions for AI agents and scrapers. Navigate, extract, click, captcha.
Fetch web pages and APIs past anti-bot walls, with reusable browser sessions.
Browser automation MCP for whole web tasks in a cloud browser: saved logins, bot checks, replays.
Related MCP Servers
- AlicenseAqualityDmaintenanceAn MCP service that automates Chrome browser control while bypassing anti-bot detection mechanisms, enabling web scraping, testing and automation on sites with sophisticated bot protection.1611MIT
- AlicenseAqualityCmaintenanceOpen-source browser automation API with anti-detection for AI agents, web scraping, and automation, providing undetectable Chrome via MCP and REST API with Cloudflare bypass.2412MIT
- AlicenseAqualityDmaintenanceStealth browser automation for AI agents, using source-patched Chromium to bypass bot detection systems like Cloudflare, reCAPTCHA, and FingerprintJS.28Apache 2.0
- AlicenseAqualityDmaintenanceEnables browser automation with anti-detection features, including navigation, interaction, form filling, and session management.2228 PyPI10MIT