SeleniumBase simplifies WebDriver testing with Python and pytest.
🚀 Start |
🏰 Features |
📚 Examples |
🎛️ Options |
🔮 Scripts |
📱 Phone
📗 APIs |
🔡 Formats |
📊 Dashboard |
🔴 Recorder |
🗾 Locales |
🌐 Grid
🎖️ GUI |
📰 TestPage |
🗂️ CasePlans |
🔎 Inspector |
🧬 Hybrid |
💻 Farm
👁️ How |
🚝 Migrate |
♻️ Templates |
🚉 NodeGUI |
📶 Charts |
🚎 Tours
🤖 CI/CD |
🕹️ JSMgr |
🌏 Translator |
🎞️ Presenter |
🛂 Boxes |
🖼️ Visual
--------Table of Contents / Navigation:
Run test_demo_site.py from examples/ (--chrome
is the default browser):
Run test_swag_labs.py from examples/ using Demo Mode:
```bash pytest test_swag_labs.py --demo ``` --------💡 SeleniumBase is a Python test framework for the Selenium/WebDriver browser automation library. This framework incorporates test-runners such as pytest
, nosetests
, and behave
to provide organized structure, test discovery, test execution, test state (eg. passed, failed, or skipped), and command-line options for changing default settings (such as choosing the browser to use). With raw Selenium, you would need to set up your own options-parser for configuring tests from the command-line.
💡 With raw Selenium, you have to manually download drivers (eg. chromedriver) before running tests. With SeleniumBase's driver manager, that's done automatically for you if the required driver isn't already on your PATH. There are also console scripts available for more control (eg. sbase get chromedriver latest
to download the latest version of chromedriver to a local SeleniumBase directory).
💡 With raw Selenium, commands that use selectors need to specify the type of selector (eg. "css selector", "button#myButton"
). With SeleniumBase, there's auto-detection between CSS Selectors and XPath, which means you don't need to specify the type of selector in your commands (but optionally you could).
💡 SeleniumBase methods often perform multiple actions in a single method call. For example, self.type(selector,text)
does the following:
1. Waits for the element to be visible.
2. Waits for the element to be interactive.
3. Clears the text field.
4. Types in the new text.
5. Presses Enter/Submit if the text ends in "\n".
With raw Selenium, those actions require multiple method calls.
💡 SeleniumBase uses default timeout values when not set, which means that methods automatically wait for elements to appear (up to the timeout limit) before failing:
✅self.click("button")
With raw Selenium, methods would fail instantly (by default) if an element needed more time to load:
❌self.driver.find_element(by="css selector", value="button").click()
(Reliable code is better than unreliable code.)
💡 SeleniumBase lets you change the explicit timeout values of methods:
✅self.click("button",timeout=10)
With raw Selenium, that requires more code:
❌WebDriverWait(driver,10).until(EC.element_to_be_clickable("css selector", "button")).click()
(Simple code is better than complex code.)
💡 SeleniumBase gives you clean error output when a test fails. With raw Selenium, error messages can get very messy.
💡 SeleniumBase gives you the option to generate a dashboard and reports for tests. It also saves screenshots from failing tests to the ./latest_logs/
folder. Raw Selenium does not have these options out-of-the-box.
💡 SeleniumBase includes desktop GUI apps for running tests, such as SeleniumBase Commander for pytest
, and SeleniumBase Behave GUI.
💡 SeleniumBase has its own Recorder & Test Generator that can create tests from manual browser actions. SeleniumBase also has many other useful tools and console scripts for getting things done quickly. (See the documentation for more details!)
📘📝 An example test with the BaseCase class. Runs with pytest or nosetests. (Learn more)
```python from seleniumbase import BaseCase class TestMFALogin(BaseCase): def test_mfa_login(self): self.open("https://seleniumbase.io/realworld/login") self.type("#username", "demo_user") self.type("#password", "secret_pass") self.enter_mfa_code("#totpcode", "GAXG2MTEOR3DMMDG") # 6-digit self.assert_exact_text("Welcome!", "h1") self.assert_element("img#image1") self.click('a:contains("This Page")') self.save_screenshot_to_logs() ```📗📝 An example test with the sb
pytest
fixture. Runs with pytest.
📙📝 An example test with the SB
Context Manager. Runs with pure python
.
📕📝 An example test with behave-BDD Gherkin structure. Runs with behave
. (Learn more)
Here's my_first_test.py:
```bash cd examples/ pytest my_first_test.py ``` > (Uses ``--chrome`` by default.)Here's the code for my_first_test.py:
```python from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_swag_labs(self): self.open("https://www.saucedemo.com") self.type("#user-name", "standard_user") self.type("#password", "secret_sauce\n") self.assert_element("div.inventory_list") self.assert_text("PRODUCTS", "span.title") self.click('button[name*="backpack"]') self.click("#shopping_cart_container a") self.assert_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.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](https://www.w3schools.com/cssref/css_selectors.asp)** are used for finding page elements. * If you're new to CSS Selectors, games like [CSS Diner](http://flukeout.github.io/) can help you learn. * For more reading, [here's an advanced guide on CSS attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors).✅ SeleniumBase automatically handles common WebDriver actions such as launching web browsers before tests, saving screenshots during failures, and closing web browsers after tests.
✅ SeleniumBase lets you customize test runs from the command-line.
✅ SeleniumBase uses simple syntax for commands. Example:
```python self.type("input", "dogs\n") ``` SeleniumBase tests can be run withpytest
or nosetests
. (There's also a behave BDD format.)
```bash
pytest my_first_test.py --chrome
nosetests test_suite.py --firefox
```
✅ pytest
includes automatic test discovery. If you don't specify a specific file or folder to run, pytest
will automatically search through all subdirectories for tests to run based on the following criteria:
✅ You can do a pre-flight check to see which tests would get discovered by pytest
before the real flight:
✅ You can be more specific when calling pytest
on a file:
✅ No More Flaky Tests! SeleniumBase methods automatically wait for page elements to finish loading before interacting with them (up to a timeout limit). This means you no longer need random time.sleep()
statements in your scripts.
Browsers: Chrome, Edge, Firefox, and Safari.
Systems: Linux/Ubuntu, macOS, and Windows.
✅ SeleniumBase works on all popular CI/CD platforms:✅ SeleniumBase includes an automated/manual hybrid solution called MasterQA, which speeds up manual testing by having automation perform all the browser actions while the manual tester handles validation.
✅ For a full list of SeleniumBase features, Click Here.
pytest
:
```bash
-v # Verbose mode. Prints the full name of each test run.
-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.
--collect-only | --co # Show what tests would get run. (Without running them)
-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:
```bash
--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".)
--cap-file=FILE # (The web browser's desired capabilities to use.)
--cap-string=STRING # (The web browser's desired capabilities to use.)
--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.)
--proxy=SERVER:PORT # (Connect to a proxy server:port for tests.)
--proxy=USERNAME:PASSWORD@SERVER:PORT # (Use 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.)
--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.)
--sjw # (Skip JS Waits for readyState to be "complete" or Angular to load.)
--pls=PLS # (Set pageLoadStrategy on Chrome: "normal", "eager", or "none".)
--headless # (Run tests in headless mode. The default arg on Linux OS.)
--headless2 # (Use the new headless mode, which supports extensions.)
--headed # (Run tests in headed/GUI mode on Linux OS, where not default.)
--xvfb # (Run tests using the Xvfb virtual display server on Linux OS.)
--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.)
--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.)
--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.)
--recorder # (Enables the Recorder for turning browser actions into 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-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.)
--use-auto-ext # (Use Chrome's automation extension.)
--uc | --undetected # (Use undetected-chromedriver to evade bot-detection.)
--uc-sub | --uc-subprocess # (Use undetected-chromedriver as a subprocess.)
--remote-debug # (Enable Chrome's Remote Debugger on http://localhost:9222)
--final-debug # (Enter Debug Mode after each test ends. 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.)
--swiftshader # (Use Chrome's "--use-gl=swiftshader" feature.)
--incognito # (Enable Chrome's Incognito mode.)
--guest # (Enable Chrome's Guest mode.)
--devtools # (Open Chrome's DevTools when the browser opens.)
--reuse-session | --rs # (Reuse the browser session between tests.)
--crumbs # (Delete all cookies between tests reusing a session.)
--disable-beforeunload # (Disable the "beforeunload" event on Chrome.)
--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.)
--visual-baseline # (Set the visual baseline for Visual/Layout tests.)
--external-pdf # (Set Chrome "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](https://github.com/seleniumbase/SeleniumBase/blob/master/seleniumbase/plugins/pytest_plugin.py)**. For detailed examples of command-line options, see **[customizing_test_runs.md](https://github.com/seleniumbase/SeleniumBase/blob/master/help_docs/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](https://github.com/seleniumbase/SeleniumBase/blob/master/seleniumbase/config/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.
```bash
cd examples/
pytest test_suite.py --browser=chrome
pytest test_suite.py --browser=firefox
```
An 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](https://github.com/seleniumbase/SeleniumBase/blob/master/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.
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.
--with-s3-logging
on the command-line when running your tests.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.)
```python
source = self.get_page_source()
head_open_tag = source.find('')
head_close_tag = source.find('', head_open_tag)
everything_inside_head = source[head_open_tag+len(''):head_close_tag]
```
🔵 Clicking:
To click an element on the page:
```python
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:
```python
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:
```python
text = self.get_text("header h2")
```
🔵 Getting the attribute value from an element on a page:
```python
attribute = self.get_attribute("#comic img", "title")
```
🔵 Asserting existence of an element on a page within some number of seconds:
```python
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:
```python
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:
```python
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:
```python
self.click('a[name*="partial_name"]')
```
🔵 Asserting visibility of text inside an element on a page within some number of seconds:
```python
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:
```python
self.assert_true(myvar1 == something)
self.assert_equal(var1, var2)
```
🔵 Useful Conditional Statements: (with creative examples)
* ``is_element_visible(selector)`` (visible on the page)
```python
if self.is_element_visible('div#warning'):
print("Red Alert: Something bad might be happening!")
```
* ``is_element_present(selector)`` (present in the HTML)
```python
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 method
```
Another example:
```python
def 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)
```python
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.")
```
🔵 Switching Tabs:
If your test opens up a new tab/window, you can switch to it. (SeleniumBase automatically switches to new tabs that don't open to about:blank
URLs.)
jQuery is a powerful JavaScript library that allows you to perform advanced actions in a web browser. If the web page you're on already has jQuery loaded, you can start executing jQuery scripts immediately. You'd know this because the web page would contain something like the following in the HTML:
```html ``` 🔵 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: ```python self.activate_jquery() ```self.generate_referral(start_page, end_page)
and the self.generate_traffic(start_page, end_page, loops)
methods.)
Let's say you want to verify multiple different elements on a web page in a single test, but you don't want the test to fail until you verified several elements at once so that you don't have to rerun the test to find more missing elements on the same page. That's where deferred asserts come in. Here's the example:
```python from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_deferred_asserts(self): self.open('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', '#middleContainer') # Will Fail self.deferred_assert_text('Random', '#middleContainer') self.deferred_assert_element('a[name="Super Fake !!!"]') # 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.
🔵 Accessing Raw WebDriver:
If you need access to any commands that come with standard WebDriver, you can call them directly like this:
```python 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.) 🔵 Retrying failing tests automatically:You can use --reruns=NUM
to retry failing tests that many times. Use --reruns-delay=SECONDS
to wait that many seconds between retries. Example:
You can use the @retry_on_exception()
decorator to retry failing methods. (First import: from seleniumbase import decorators
). To learn more about SeleniumBase decorators, click here.