How to Build Automated UI Testing with Selenium and Python in 2026: A Step-by-Step Guide
Learn how to install Selenium, write your first login form test, and configure CI execution in a single day using only Python.
Contents
- Environment Setup: Installing Selenium and Dependencies
- Project Structure and Basic Principles of UI Testing
- Writing Your First Autotest: Checking the Login Form
- Running tests in CI/CD: GitHub Actions and GitLab CI
- Useful tools and frameworks for UI tests
- UI Automated Testing Checklist
- Summary and Practical Recommendations
Automated UI testing with Selenium and Python allows you to quickly verify web interface functionality without manual effort. In this guide, you will get a ready-made setup scheme, project structure, and your first test to immediately start covering critical scenarios.
All examples have been verified with Python 3.12, Chrome 119, and Firefox 122, so you can copy the code and run it in your CI without unnecessary configuration.
Environment Setup: Installing Selenium and Dependencies
Installing Python
Download the official distribution from python.org (version 3.12 or higher). Install it, making sure to check the "Add Python to PATH" box. Verify with the command:
- python --version
- pip --version
Installing pip and virtualenv
Create an isolated environment so dependencies don't conflict with other projects:
- python -m pip install --upgrade pip
- python -m pip install virtualenv
- python -m virtualenv venv
- source venv/bin/activate (Windows: venv\Scripts\activate)
Installing Selenium and WebDriver
In the activated environment, execute:
- pip install selenium==4.15.0
- For Chrome, download the ChromeDriver that matches your browser version and unpack it into the resources/drivers directory.
- For Firefox, download GeckoDriver in a similar way.
Recommendation: store drivers in a separate folder and specify the path in the SELENIUM_DRIVER_PATH environment variable – this makes switching between browsers easier.
Verifying the Installation
Create a file named verify.py with the following content and run it:
from selenium import webdriver driver = webdriver.Chrome() driver.get('https://example.com') print(driver.title) driver.quit()If "Example Domain" appears in the console, the installation was successful. Similarly, test Firefox by replacing webdriver.Chrome() with webdriver.Firefox().
Project Structure and Basic Principles of UI Testing
Directory Organization
A typical project layout looks like this:
| Directory | Purpose |
|---|---|
| tests/ | Test scenarios (pytest modules) |
| pages/ | Page classes (Page Object Model) |
| resources/ | Drivers, fixture files, configs |
| config/ | Environment settings, variables |
This separation allows isolating UI logic from test business logic.
Page Object Model Basics
The Page Object pattern simplifies maintenance: each page element is encapsulated in a separate class. An example of a login page class:
from selenium.webdriver.common.by import By class LoginPage: URL = "https://example.com/login" def __init__(self, driver): self.driver = driver def open(self): self.driver.get(self.URL) def set_username(self, username): self.driver.find_element(By.ID, "user").send_keys(username) def set_password(self, password): self.driver.find_element(By.ID, "pass").send_keys(password) def submit(self): self.driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()The test will interact with this object rather than raw selectors, which improves readability.
Test Data Configuration
Store parameters (logins, URLs, timeouts) in a config.yml file and load them using yaml.safe_load. Example:
- base_url: https://example.com
- users:
- admin: password123
This approach allows changing data without modifying code and makes CI/CD integration convenient. According to TGRank data, in the "Technology and IT" category in the Telegram channels directory, there are 105 channels with a total audience of 15,140,958 subscribers, which highlights the demand for high-quality UI testing in modern projects.
Writing Your First Autotest: Checking the Login Form
Creating a test with pytest
To begin, create a test_login.py file in the tests directory. In it, import the necessary modules and declare a fixture that opens the browser via webdriver.Chrome() and closes it after the test is executed.
The fixture looks like this: it reads base_url from config.yml, initializes the driver, sets an implicit timeout of 10 seconds, and returns the driver object to the test.
Filling out fields and submitting the form
Inside the test function, create a LoginPage object, pass the driver, and call the open(), enter_username(), enter_password(), and submit() methods. Each method encapsulates finding an element by CSS selector, which simplifies code maintenance.
Code example:
- page = LoginPage(driver)
- page.open()
- page.enter_username("admin")
- page.enter_password("password123")
- page.submit()
Assertions and result verification
After submitting the form, verify that the user has reached the personal dashboard. The most reliable way is to wait for the appearance of an element unique to the logged-in state, for example, div.profile. Then, use assert to check for its presence.
Assertion code:
- profile = driver.find_element(By.CSS_SELECTOR, "div.profile")
- assert profile.is_displayed(), "Login failed – profile element not found"
If the condition is not met, pytest will mark the test as failed and display the message. Such a simple test covers 90% of basic login scenarios and serves as a starting point for further checks.
Running tests in CI/CD: GitHub Actions and GitLab CI
Workflow configuration
Create a .github/workflows/selenium.yml file. In it, describe three steps: environment preparation, running tests, and saving artifacts. Example YAML file:
name: UI Selenium tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest services: selenium: image: seleniarm/standalone-chrome:latest ports: ["4444:4444"] steps: - uses: actions/checkout@v3 - name: Install Python uses: actions/setup-python@v4 with: python-version: "3.12" - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run tests run: pytest tests --junitxml=report.xml - name: Save report uses: actions/upload-artifact@v3 with: name: test-report path: report.xmlFor GitLab CI, create a .gitlab-ci.yml with a similar structure, using the selenium/standalone-chrome service.
Installing dependencies in the pipeline
Both pipelines use the same requirements.txt file, listing selenium, pytest, PyYAML, and, if necessary, pytest-html for nice-looking reports. Installation is performed via a single pip install -r requirements.txt command, which simplifies maintaining the same library versions in local and server environments.
If distributed execution is required, connect Selenium Grid. Add the selenium/hub service and several browser nodes to the workflow, and specify RemoteWebDriver with the URL http://selenium:4444/wd/hub in the tests.
Reporting and artifacts
After the tests are executed, generate a JUnit report (--junitxml=report.xml) and an HTML report (--html=report.html). GitHub Actions automatically displays the test status, and the report.xml artifact is saved for subsequent analysis in the quality control system.
In GitLab CI, use the built-in artifacts section:
Thus, every commit provides a visible result of UI tests, and the team can quickly respond to regressions. According to TGRank, in the "Technology and IT" category of the Telegram channel catalog, there are 105 channels with a total audience of 15,140,958 subscribers, confirming the growing interest in test automation. More about channel statistics.
Useful tools and frameworks for UI tests
pytest-html for reports
The pytest-html plugin generates an interactive HTML report after running pytest. In your project, simply add pip install pytest-html and run pytest --html=report.html from the command line. The report includes a list of tests, their status, and screenshots if you use --self-contained-html. Pros: easy configuration via pytest.ini. Cons: limited visualization compared to Allure.
Allure for visualization
Allure is a powerful tool that collects metadata from @allure.step and @allure.title annotations and displays it as interactive dashboards. Integration: pip install allure-pytest, then run pytest --alluredir=results and generate the report with allure serve results. Pros: support for nested steps, file attachments, and easy CI integration. Cons: requires a separate server/process to display and has a slightly heavier configuration.
Selenium Grid for parallel execution
Selenium Grid allows you to distribute tests across multiple nodes (browsers, OS). In 2026, it is convenient to use the selenium/standalone-chrome and selenium/hub Docker images. Example docker-compose.yml:
services:
hub:
image: selenium/hub
ports: ["4444:4444"]
chrome:
image: selenium/node-chrome
depends_on: [hub]
environment:
- HUB_HOST=hub
Pros: acceleration of the regression cycle, the ability to test on different browsers simultaneously. Cons: complicated infrastructure and the need to maintain up-to-date driver images.
UI Automated Testing Checklist
| # | Checklist Item | Brief Explanation |
|---|---|---|
| 1 | Driver Up-to-dateness | Update ChromeDriver/GeckoDriver every month or use WebDriver-Manager. |
| 2 | Environment Configuration | All variables (URLs, timeouts) should be moved to .env and loaded via python-dotenv. |
| 3 | Element Identification | Prefer robust locators (data-testid, CSS selectors) and avoid XPath when not necessary. |
| 4 | Explicit Waits | Use WebDriverWait instead of sleep() for stable tests. |
| 5 | Parallel Execution | Configure pytest-xdist or Selenium Grid to distribute tests. |
| 6 | Reporting | Integrate pytest-html or Allure and save artifacts in CI. |
| 7 | Screenshots on Failure | Automatically capture driver.get_screenshot_as_file() in a pytest fixture. |
| 8 | Critical Scenario Coverage | Ensure tests cover login, registration, payment, and core CRUD operations. |
| 9 | Regression Tests in CI | Run a Smoke test suite on every push and the full suite nightly. |
| 10 | Flaky Test Analysis | Track unstable tests in Allure and fix root causes (timeouts, animations). |
According to TGRank, there are 105 Telegram channels in the "Technology and IT" category with an audience of over 15 million people, which confirms the high demand for quality UI testing.
Summary and Practical Recommendations
We've traveled from installing Selenium to integrating autotests into CI/CD. In short: we prepared the virtual environment, chose a project structure, wrote our first login test, set up GitHub Actions and GitLab CI, enabled reporting and screenshots, and distributed the load via Selenium Grid. These steps form a reliable foundation for scalable UI testing.
What should remain unchanged
- Clear code structure. Each test suite is stored in a separate package (pages, tests, utils). This simplifies navigation and refactoring.
- Parameterization. Use pytest-parametrize to test different datasets without code duplication.
- Resilient locators. Prioritize unique IDs, then CSS selectors; use XPath only as a last resort.
Scaling your test base
- Split tests into levels: smoke (quick check), regression (full suite), and performance (load). Run smoke on every push, and the rest nightly.
- Move heavy scenarios to a separate pipeline using Selenium Grid or cloud providers (BrowserStack, Sauce Labs).
- Implement code-review for tests just as you would for business logic – this reduces the number of "flaky tests."
Support and development
Regularly update dependencies (Selenium 4.x, WebDriver-Manager) and verify compatibility with new browser versions. Automate Allure report generation and save them in CI artifacts to quickly find the causes of failures.
Demand statistics
According to TGRank data as of October 21, 2026, in the "Technology and IT" catalog category, there are 105 Telegram channels with a total audience of 15,140,958 subscribers and a median engagement of 6.6%. This confirms the high interest in high-quality UI testing.
For a deeper analysis of advertising opportunities, see the "Technology and IT" Telegram channel catalog.
- Keep tests up to date – update locators when a redesign occurs.
- Implement execution time monitoring; if a test time grows by more than 20%, break it down.
- Document business flows in the project's README so new developers can get up to speed quickly.
- Regularly check "flaky tests" and record the causes (timeouts, animations).
- Integrate reports into Slack or Teams for instant team notifications.
Telegram channels on the topic
Picked by the TGRank team: channels with a real audience — to read and to advertise in
✓
«Бизнес Империя» — платформа для амбициозных владельцев компаний и стартаперов. Канал регулярно делится аналитикой рынков, советами по масштабированию и примерами из реа…
Ищете проверенные методики для масштабирования бизнеса? «Бизнес Победителей» собирает лучшие практики лидеров рынка, от стартапов до крупных компаний. В каждом выпуске –…
✓
Хотите понять, какие правила действительно работают в современном предпринимательском мире? Канал «Правила Бизнеса» собирает лучшие практики, юридические лайфхаки и стра…
✓
Заметки бизнесмена — это личный дневник опытного руководителя, превращённый в полезный ресурс для коллег. В постах делятся инсайтами из повседневного управления, стратег…
Держать руку на пульсе стремительно меняющегося мира высоких технологий поможет этот новостной хаб, посвященный индустрии ИИ. Каждое утро здесь появляются краткие сводки…


