0
0
Selenium Pythontesting~8 mins

Find element by XPath in Selenium Python - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Find element by XPath
Folder Structure
selenium_project/
├── src/
│   ├── pages/
│   │   └── login_page.py
│   ├── tests/
│   │   └── test_login.py
│   ├── utils/
│   │   └── helpers.py
│   └── config/
│       └── config.py
├── drivers/
│   └── chromedriver.exe
├── requirements.txt
└── pytest.ini
    
Test Framework Layers
  • Driver Layer: Manages WebDriver setup and teardown (e.g., ChromeDriver).
  • Page Objects: Classes representing web pages, locating elements by XPath and other locators.
  • Tests: Test cases using page objects to perform actions and assertions.
  • Utilities: Helper functions like waits, logging, and common actions.
  • Configuration: Environment settings, URLs, credentials, and browser options.
Configuration Patterns

Use a config.py file to store environment URLs, browser choices, and credentials. Use environment variables or separate config files for different environments (dev, test, prod).

# config/config.py
BASE_URL = "https://example.com"
BROWSER = "chrome"
USERNAME = "testuser"
PASSWORD = "password123"
    
Test Reporting and CI/CD Integration

Use pytest with plugins like pytest-html for readable reports. Integrate tests in CI/CD pipelines (GitHub Actions, Jenkins) to run tests on each commit and publish reports.

# pytest.ini
[pytest]
addopts = --html=reports/report.html --self-contained-html
    
Best Practices
  • Use Page Object Model: Keep XPath locators inside page classes to separate test logic from UI details.
  • Prefer Explicit Waits: Use Selenium's WebDriverWait with conditions to wait for elements located by XPath.
  • Keep XPath Simple and Stable: Avoid brittle or overly complex XPath expressions; prefer attributes or IDs when possible.
  • Parameterize XPath: Use methods to build XPath dynamically for reusable locators.
  • Store Locators as Constants: Define XPath strings as constants or class variables for easy maintenance.
Self Check

Where in this folder structure would you add a new XPath locator for a "Submit" button on the login page?

Key Result
Organize Selenium Python tests using Page Object Model with XPath locators inside page classes, explicit waits, and clear config for maintainability.