0
0
Selenium Pythontesting~8 mins

Absolute vs relative XPath in Selenium Python - Framework Approaches Compared

Choose your learning style9 modes available
Framework Mode - Absolute vs relative XPath
Folder Structure
selenium_python_project/
├── tests/
│   ├── test_login.py
│   ├── test_search.py
│   └── test_navigation.py
├── pages/
│   ├── base_page.py
│   ├── login_page.py
│   └── search_page.py
├── utils/
│   ├── xpath_helpers.py
│   └── wait_utils.py
├── config/
│   ├── config.yaml
│   └── credentials.yaml
├── conftest.py
└── requirements.txt
    
Test Framework Layers
  • Driver Layer: Manages browser setup and teardown using Selenium WebDriver in conftest.py.
  • Page Objects: Classes in pages/ folder represent web pages. They use relative XPath locators for flexibility and maintainability.
  • Tests: Test scripts in tests/ folder use page objects to perform actions and assertions.
  • Utilities: Helper functions like XPath builders or wait helpers in utils/ to support tests and page objects.
  • Configuration: Environment settings, URLs, credentials stored in config/ files for easy updates.
Configuration Patterns

Use config.yaml to store environment URLs and browser preferences. Use credentials.yaml for sensitive data like usernames and passwords.

Example config.yaml snippet:

environment: staging
browser: chrome
base_url: "https://staging.example.com"
    

Load these configs in conftest.py to initialize WebDriver and tests dynamically.

Test Reporting and CI/CD Integration
  • Use pytest with pytest-html plugin to generate readable HTML reports after test runs.
  • Integrate tests into CI/CD pipelines (e.g., GitHub Actions, Jenkins) to run tests automatically on code changes.
  • Reports help quickly identify if XPath locators (absolute or relative) fail due to UI changes.
Best Practices for Absolute vs Relative XPath
  1. Prefer relative XPath: It is shorter, more flexible, and less likely to break when UI changes.
  2. Avoid absolute XPath: It starts from root and is brittle because any change in page structure breaks it.
  3. Use meaningful attributes: Build relative XPath using stable attributes like id, name, or class.
  4. Keep locators maintainable: Store XPath expressions in page objects or utility files for easy updates.
  5. Test XPath in browser DevTools: Verify XPath expressions before adding to code to ensure they select the right elements.
Self Check

Where in this framework structure would you add a new relative XPath locator for a button on the login page?

Key Result
Use relative XPath in page objects for flexible and maintainable element locating in Selenium Python frameworks.