TGRank — Telegram channel marketplace
TGRank
Your independent guide to Telegram stats
Каналы
Русскоязычные922Україна133Oʻzbekiston50English221فارسی113World1 415
Язык сайта
27 Users
26 per day
0 Online
Log in with TelegramLog in
Technology & IT

How to Build Automated UI Testing with Selenium and Python in 2026: A Step-by-Step Guide

TGRank editorial team November 23, 2026 9 min read
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
  1. Environment Setup: Installing Selenium and Dependencies
  2. Project Structure and Basic Principles of UI Testing
  3. Writing Your First Autotest: Checking the Login Form
  4. Running tests in CI/CD: GitHub Actions and GitLab CI
  5. Useful tools and frameworks for UI tests
  6. UI Automated Testing Checklist
  7. 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:

  1. python -m pip install --upgrade pip
  2. python -m pip install virtualenv
  3. python -m virtualenv venv
  4. source venv/bin/activate (Windows: venv\Scripts\activate)

Installing Selenium and WebDriver

In the activated environment, execute:

  1. pip install selenium==4.15.0
  2. For Chrome, download the ChromeDriver that matches your browser version and unpack it into the resources/drivers directory.
  3. 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:

DirectoryPurpose
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:

  1. profile = driver.find_element(By.CSS_SELECTOR, "div.profile")
  2. 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.xml

For 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:

artifacts: when: always reports: junit: report.xml paths: - report.html

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 ItemBrief Explanation
1Driver Up-to-datenessUpdate ChromeDriver/GeckoDriver every month or use WebDriver-Manager.
2Environment ConfigurationAll variables (URLs, timeouts) should be moved to .env and loaded via python-dotenv.
3Element IdentificationPrefer robust locators (data-testid, CSS selectors) and avoid XPath when not necessary.
4Explicit WaitsUse WebDriverWait instead of sleep() for stable tests.
5Parallel ExecutionConfigure pytest-xdist or Selenium Grid to distribute tests.
6ReportingIntegrate pytest-html or Allure and save artifacts in CI.
7Screenshots on FailureAutomatically capture driver.get_screenshot_as_file() in a pytest fixture.
8Critical Scenario CoverageEnsure tests cover login, registration, payment, and core CRUD operations.
9Regression Tests in CIRun a Smoke test suite on every push and the full suite nightly.
10Flaky Test AnalysisTrack 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

  1. Split tests into levels: smoke (quick check), regression (full suite), and performance (load). Run smoke on every push, and the rest nightly.
  2. Move heavy scenarios to a separate pipeline using Selenium Grid or cloud providers (BrowserStack, Sauce Labs).
  3. 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

Бизнес Империя ✓
Бизнес Империя
19,8K subscribers 12K post reach ERR 61%

«Бизнес Империя» — платформа для амбициозных владельцев компаний и стартаперов. Канал регулярно делится аналитикой рынков, советами по масштабированию и примерами из реа…

Ads from5 000 ₽
Бизнес Победителей ✓
Бизнес Победителей
79,4K subscribers 51,1K post reach ERR 64%

Ищете проверенные методики для масштабирования бизнеса? «Бизнес Победителей» собирает лучшие практики лидеров рынка, от стартапов до крупных компаний. В каждом выпуске –…

Ads from14 500 ₽
Правила Бизнеса ✓
Правила Бизнеса
74K subscribers 40,7K post reach ERR 55%

Хотите понять, какие правила действительно работают в современном предпринимательском мире? Канал «Правила Бизнеса» собирает лучшие практики, юридические лайфхаки и стра…

Ads from14 005 ₽
Заметки Бизнесмена ✓
Заметки Бизнесмена
41K subscribers 13,9K post reach ERR 34%

Заметки бизнесмена — это личный дневник опытного руководителя, превращённый в полезный ресурс для коллег. В постах делятся инсайтами из повседневного управления, стратег…

Ads from6 500 ₽
эйай ньюз
эйай ньюз
98,7K subscribers 29,1K post reach ERR 29%

Держать руку на пульсе стремительно меняющегося мира высоких технологий поможет этот новостной хаб, посвященный индустрии ИИ. Каждое утро здесь появляются краткие сводки…

Sachok
Sachok
11,4K subscribers 3,3K post reach ERR 29%

Хотите быть в курсе самых свежих новостей из мира технологий, не тратя время на скучные лонгриды? Канал «Sachok» предлагает лаконичные и емкие заметки о главных событиях…

% Ads in several channels at once — cheaperBundles on TGRank: up to 40% off when you book a package View → All channels in the category «Technology & IT» →

FAQ

How to install Selenium for Python?
Install Python 3, create a virtual environment, and then run `pip install selenium`. After that, download the appropriate WebDriver (ChromeDriver or GeckoDriver) and add it to your PATH.
How to write tests for a login form?
Structure your test using the Page Object pattern: create a page class with methods for entering login and password, then call them in your test and verify the successful redirect using assert.
How to run tests in CI?
Add a CI configuration file to your repository (GitHub Actions `.yml` or GitLab `.gitlab-ci.yml`) that describes the steps for installing dependencies, launching Selenium-WebDriver, and executing `pytest`.
Is it possible to run multiple UI tests in parallel?
Yes, use Selenium Grid or pytest-xdist; they distribute tests across multiple browser nodes, speeding up the overall execution.
Which reports are best for UI tests?
For simple reports, `pytest-html` is suitable, while for more visual ones, use Allure, which displays screenshots, logs, and execution steps.
What should I do if tests are flaky due to UI instability?
Implement explicit waits (`WebDriverWait`), avoid hard-coded `sleep` commands, and ensure that elements are in an interactive state before performing actions.
TGRank editorial team