keepcalculator

06 Numbers and Powers

Playwright Python Page Objects: Organize Tests

Card No. 06·21991 · Updated · Standard formula, shown below

This guide shows you how to structure your Playwright Python tests using the Page Object Model (POM). You’ll learn to separate page-specific locators and actions into reusable classes, making your tests cleaner, more maintainable, and less brittle when the UI changes. We’ll cover the core pattern, a step-by-step implementation, and common pitfalls to avoid.

What You’ll Need

  • Python 3.7 or later installed
  • Playwright for Python installed (pip install playwright) and browsers set up (playwright install)
  • A basic understanding of Python classes and pytest (or another test runner)
  • An existing or new Playwright test project

Step-by-Step

  1. Create a directory structure for your page objects. A common pattern is to keep page classes in a pages/ folder, separate from your test files. For example:
    project_root/
    ├── pages/
    │   ├── __init__.py
    │   ├── login_page.py
    │   └── dashboard_page.py
    ├── tests/
    │   ├── conftest.py
    │   └── test_login.py
    └── requirements.txt
  2. Define a base page class (optional but recommended). Create a base_page.py that holds common methods like navigate(), wait_for_element(), or a reference to the page object. This reduces duplication across your page classes.
    # pages/base_page.py
    class BasePage:
        def __init__(self, page):
            self.page = page
    
        def navigate(self, url):
            self.page.goto(url)
    
        def wait_for_selector(self, selector):
            self.page.wait_for_selector(selector)
  3. Create a page class for each page of your application. For example, a login page class would contain locators for username, password, and login button, plus methods like login(username, password). Use Playwright’s get_by_role, get_by_label, or CSS selectors for robust locators.
    # pages/login_page.py
    from .base_page import BasePage
    
    class LoginPage(BasePage):
        # Locators
        USERNAME_INPUT = "#username"
        PASSWORD_INPUT = "#password"
        LOGIN_BUTTON = "button[type='submit']"
    
        def __init__(self, page):
            super().__init__(page)
    
        def fill_username(self, username):
            self.page.fill(self.USERNAME_INPUT, username)
    
        def fill_password(self, password):
            self.page.fill(self.PASSWORD_INPUT, password)
    
        def click_login(self):
            self.page.click(self.LOGIN_BUTTON)
    
        def login(self, username, password):
            self.fill_username(username)
            self.fill_password(password)
            self.click_login()
  4. In your test, instantiate the page object and use its methods. Pass the Playwright page fixture (from pytest) to the page object constructor. This keeps your test logic clean and readable.
    # tests/test_login.py
    from pages.login_page import LoginPage
    
    def test_login_success(page):
        login_page = LoginPage(page)
        login_page.navigate("https://example.com/login")
        login_page.login("user", "pass")
        # Assert something on the dashboard
        assert page.url == "https://example.com/dashboard"
  5. Return page objects from methods that navigate to another page. For example, after a successful login, the login() method could return a DashboardPage instance. This creates a fluent, chained flow.
    # In LoginPage
    from .dashboard_page import DashboardPage
    
    def login(self, username, password):
        self.fill_username(username)
        self.fill_password(password)
        self.click_login()
        return DashboardPage(self.page)
  6. Use pytest fixtures to manage the page object lifecycle. In your conftest.py, you can create fixtures that instantiate page objects, so tests can request them directly.
    # tests/conftest.py
    import pytest
    from pages.login_page import LoginPage
    
    @pytest.fixture
    def login_page(page):
        return LoginPage(page)
  7. Keep your locators in one place. All CSS/XPath selectors for a page should live as class attributes or constants at the top of the page class. This way, when the UI changes, you only update the locator in one spot.
  8. Run your tests regularly. Use pytest to execute your suite. Make sure your page objects are imported correctly and the test runner can find them.

Common Mistakes

  • Putting assertions inside page objects. Page objects should only interact with the page, not verify outcomes. Assertions belong in your test functions.
  • Hard-coding URLs in tests. Store base URLs in a config file or environment variable, and let page objects accept them as parameters.
  • Using brittle locators like //div[1]/span. Prefer semantic locators like get_by_role or get_by_label that are less likely to break.
  • Creating a new page object instance for every action. Reuse instances where possible, or return the next page object from methods to maintain context.
  • Ignoring waits. Playwright auto-waits for actions, but if you manually use page.wait_for_timeout(), you’re introducing flakiness. Use explicit waits for specific conditions instead.

Tips

  • Start with a few pages. Don’t over-engineer. Create page objects for pages you actually test, and refactor as your suite grows.
  • Use a naming convention. Suffix page classes with Page (e.g., LoginPage) to avoid confusion.
  • Keep page objects stateless. They should not store data between calls; rely on the underlying page object for state.
  • Leverage Playwright’s built-in assertions. Use expect() from playwright.sync_api for robust, auto-retrying checks.
  • Document your locators. Add comments explaining what each locator targets, especially if the selector is complex.

Troubleshooting

Tests fail with “Element not found” or timeout. This often means your locator is wrong or the element is not yet visible. Double-check the selector using Playwright’s codegen or inspector. Also, ensure your page object is using the correct page instance – passing a new page fixture to each test is fine, but don’t mix instances.

Page object methods return None when you expect a page object. Make sure your method actually returns the new page object. For example, return DashboardPage(self.page) – not just self.page.

Imports fail. Check your relative imports. If you’re using from .base_page import BasePage, ensure the pages directory has an __init__.py file. Alternatively, use absolute imports if your project structure is flat.

Tests run but don’t see the page objects. Add the project root to your PYTHONPATH or install your package in editable mode (pip install -e .) so pytest can find your modules.

Playwright doesn’t wait for navigation. If you click a button that triggers navigation, Playwright usually waits automatically. If not, use page.expect_navigation() around the click, or rely on the auto-waiting of click().

Frequently Asked Questions

Do I need a base page class?

No, it’s optional. It helps if you have many common actions (like navigation or waiting). For small projects, you can skip it and keep each page class self-contained.

Can I use page objects with pytest-playwright?

Yes, absolutely. The page fixture provided by pytest-playwright is perfect for passing into your page object constructors.

How do I handle dynamic elements like loading spinners?

Use explicit waits in your page object methods, e.g., self.page.wait_for_selector(".spinner", state="hidden") or rely on Playwright’s auto-waiting for actions.

Should I test through the UI or use API calls?

For end-to-end tests, UI is necessary. But for faster feedback, consider mixing API-based setup (e.g., creating test data) with UI assertions. Page objects can encapsulate both.

How do I manage multiple environments (dev, staging)?

Use environment variables or a config file to store base URLs. Pass the URL to your page object’s navigate() method, or set it as a fixture.

What’s the best way to organize locators?

Keep them as class attributes at the top of the page class, grouped by section (e.g., form fields, buttons, navigation). This makes it easy to update when selectors change.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →