0
0
Selenium Pythontesting~8 mins

Element locators in page class in Selenium Python - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Element locators in page class
Folder Structure
project_root/
├── src/
│   └── pages/
│       └── login_page.py
├── tests/
│   └── test_login.py
├── utils/
│   └── helpers.py
├── config/
│   └── config.yaml
├── conftest.py
└── requirements.txt
    
Test Framework Layers
  • Driver Layer: Manages browser setup and teardown (e.g., in conftest.py using pytest fixtures).
  • Page Objects: Classes representing pages, containing element locators and methods to interact with them (e.g., login_page.py).
  • Tests: Test scripts that use page objects to perform actions and assertions (e.g., test_login.py).
  • Utilities: Helper functions or classes for common tasks like waits or data handling (e.g., helpers.py).
  • Configuration: Files and code to manage environment variables, URLs, credentials (e.g., config.yaml).
Configuration Patterns

Use a config.yaml file to store environment URLs, browser types, and credentials securely.

Load configuration in conftest.py or utility modules to initialize tests dynamically.

Example snippet to load config:

import yaml

with open('config/config.yaml') as f:
    config = yaml.safe_load(f)

browser = config['browser']
base_url = config['base_url']
credentials = config['credentials']
Test Reporting and CI/CD Integration
  • Use pytest's built-in reporting with --junitxml=report.xml for CI tools.
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins) to run tests on each commit.
  • Generate HTML reports using plugins like pytest-html for readable test results.
  • Fail tests clearly when element locators are not found, aiding quick debugging.
Best Practices for Element Locators in Page Classes
  1. Use descriptive variable names for locators to make code readable (e.g., username_input).
  2. Keep locators private (prefix with underscore) and expose interaction methods instead.
  3. Use stable locator strategies like By.ID or By.CSS_SELECTOR over brittle XPaths.
  4. Centralize locators in page classes to ease maintenance when UI changes.
  5. Use explicit waits in page methods to handle dynamic elements reliably.
Self Check

Where in this folder structure would you add a new locator for the "Remember Me" checkbox on the login page?

Key Result
Organize element locators inside page classes to keep tests clean, maintainable, and reliable.