0
0
Selenium Pythontesting~8 mins

XPath with contains and starts-with in Selenium Python - Framework Patterns

Choose your learning style9 modes available
Framework Mode - XPath with contains and starts-with
Folder Structure
selenium_python_project/
├── src/
│   ├── pages/
│   │   └── login_page.py          # Page Object classes with XPath locators
│   ├── tests/
│   │   └── test_login.py           # Test cases using page objects
│   ├── utils/
│   │   └── helpers.py              # Utility functions (e.g., wait helpers)
│   └── config/
│       └── config.yaml             # Environment and browser settings
├── requirements.txt                # Python dependencies
├── pytest.ini                     # Pytest configuration
└── conftest.py                    # Fixtures for setup/teardown
    
Test Framework Layers
  • Driver Layer: Manages WebDriver setup and teardown (in conftest.py).
  • Page Objects: Classes in src/pages/ define web elements using XPath with contains() and starts-with() for flexible locators.
  • Tests: Test scripts in src/tests/ use page objects to perform actions and assertions.
  • Utilities: Helper functions for waits, logging, or data handling in src/utils/.
  • Configuration: Environment variables, browser options, and credentials stored in src/config/config.yaml.
Configuration Patterns

Use a YAML file (config.yaml) to store environment URLs, browser choices, and credentials. Load this config in conftest.py to initialize WebDriver accordingly.

# Example config.yaml
base_url: "https://example.com"
browser: "chrome"
credentials:
  username: "testuser"
  password: "securepass"
    

This keeps sensitive data separate and allows easy switching between environments.

Test Reporting and CI/CD Integration
  • Use pytest with plugins like pytest-html to generate readable HTML reports.
  • Integrate tests into CI/CD pipelines (e.g., GitHub Actions, Jenkins) to run tests automatically on code changes.
  • Reports help quickly see which XPath locators passed or failed, especially those using contains() and starts-with().
Best Practices
  • Use contains() in XPath to locate elements with partial attribute values, making tests resilient to small UI changes.
  • Use starts-with() to match elements whose attributes begin with a known string, useful for dynamic IDs.
  • Keep XPath expressions readable and maintainable by defining them as variables or constants in page objects.
  • Use explicit waits to ensure elements located by XPath are present before interacting.
  • Separate locators from test logic by using the Page Object Model for cleaner, reusable code.
Self Check

Where in this framework structure would you add a new XPath locator using contains() for a "Sign Up" button?

Key Result
Use Page Object Model with XPath contains() and starts-with() for flexible, maintainable element locators in Selenium Python tests.