0
0
Selenium Pythontesting~8 mins

Getting element text in Selenium Python - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Getting element text
Folder Structure
selenium_python_project/
├── src/
│   ├── pages/
│   │   └── home_page.py
│   ├── tests/
│   │   └── test_home_page.py
│   ├── utils/
│   │   └── helpers.py
│   └── config/
│       └── config.py
├── requirements.txt
└── pytest.ini
    
Test Framework Layers
  • Driver Layer: Manages browser setup and teardown using Selenium WebDriver.
  • Page Objects: Classes representing web pages, with methods to interact with elements and get their text.
  • Tests: Test scripts that use page objects to perform actions and assert element text.
  • Utilities: Helper functions for common tasks like waiting for elements or logging.
  • Configuration: Settings for environment URLs, browser types, and credentials.
Configuration Patterns

Use a config.py file to store environment URLs and browser options. Use environment variables or command-line options to switch between environments (e.g., dev, staging, prod) and browsers (e.g., Chrome, Firefox).

# config/config.py
ENVIRONMENTS = {
    "dev": "https://dev.example.com",
    "staging": "https://staging.example.com",
    "prod": "https://example.com"
}

BROWSER = "chrome"  # or "firefox"
    
Test Reporting and CI/CD Integration

Use pytest with plugins like pytest-html to generate readable HTML reports showing which tests passed or failed, including screenshots on failure.

Integrate tests into CI/CD pipelines (e.g., GitHub Actions, Jenkins) to run tests automatically on code changes and publish reports.

Best Practices
  • Use Page Object Model: Encapsulate element locators and methods like get_element_text() inside page classes for easy reuse.
  • Use Explicit Waits: Wait for elements to be visible before getting text to avoid flaky tests.
  • Keep Locators Simple and Stable: Use unique IDs or data-test attributes to locate elements reliably.
  • Separate Test Logic from UI Interaction: Tests should call page methods, not directly access Selenium WebDriver.
  • Use Clear Assertions: Assert the exact expected text to catch UI regressions early.
Self Check

Where would you add a new method get_element_text() for a button on the home page in this framework structure?

Key Result
Use Page Object Model with explicit waits to get element text reliably in Selenium Python tests.