Page Object Model in Playwright Python Step by Step
When ten tests all contain page.get_by_test_id("login-username"), a single change to the login form breaks ten files. The Page Object Model (POM) fixes that by giving every page of the application one Python class that knows its locators and actions. Tests then read like user stories: log in, search, add to cart. In this lesson you will refactor real SQA Shop tests into page objects step by step: a base page, page classes with locators and actions, methods that return the next page, a shared header component, pytest fixtures that hand out page objects, and the rules that keep a POM clean as it grows.
📖 What You’ll Learn: the problem POM solves, what belongs in a page object and what does not, a BasePage, locators defined once in init, action methods, methods that return the next page object, keeping assertions in tests, small assertion helpers, components for shared parts like the header, page-object fixtures in conftest.py, and common POM mistakes.
😖 The Problem: Locators Everywhere
Here are two ordinary tests for the SQA Shop:
📄 pytest.ini
[pytest]
addopts = --base-url https://sqatools.in
pythonpath = .
pythonpath = . puts the project root on Python’s import path, so tests can import pages... from the pages/ folder you are about to create.
📄 tests/test_before_pom.py
from playwright.sync_api import Page, expect
SHOP = "/dummy-ecommerce-website/"
def test_login_and_add_to_cart(page: Page):
page.goto(SHOP + "#/login")
page.get_by_test_id("login-username").fill("testuser")
page.get_by_test_id("login-password").fill("Test@123")
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
page.get_by_test_id("search-input").fill("earbuds")
page.get_by_test_id("search-button").click()
page.get_by_role("button", name="Add to cart").first.click()
expect(page.get_by_test_id("cart-count")).to_have_text("1")
def test_coupon(page: Page):
page.goto(SHOP + "#/login")
page.get_by_test_id("login-username").fill("testuser")
page.get_by_test_id("login-password").fill("Test@123")
page.get_by_test_id("login-button").click()
page.get_by_test_id("search-input").fill("earbuds")
page.get_by_test_id("search-button").click()
page.get_by_role("button", name="Add to cart").first.click()
page.goto(SHOP + "#/cart")
page.get_by_test_id("coupon-input").fill("SAVE10")
page.get_by_test_id("apply-coupon").click()
expect(page.get_by_test_id("coupon-message")).to_have_text("Coupon SAVE10 applied.")
⌨️ Terminal
pytest tests/test_before_pom.py -q
🖥️ Output
.. [100%]
2 passed in 4.07s
They pass, but:
- The login steps are copied. If the login form changes, every copy must change.
- A reader must decode locators to understand the intent: what does
get_by_test_id("apply-coupon")mean for the business? - Nothing stops one test from using a slightly different (and worse) locator for the same button.
🧱 Step 1: A Base Page
A page object is a class that represents one page (or one view of a single-page app). It holds the Playwright Page and exposes the page’s elements and actions. Start with a small base class for what all pages share:
📄 pages/base_page.py
from playwright.sync_api import Page
SHOP = "/dummy-ecommerce-website/"
class BasePage:
"""Shared plumbing for all SQA Shop pages."""
path = "" # each page sets its own route, e.g. "#/login"
def __init__(self, page: Page):
self.page = page
def open(self):
self.page.goto(SHOP + self.path)
return self
open() returns self, so a test can write LoginPage(page).open().login(...).
🔐 Step 2: The Login Page
Define each locator once, in __init__, with a name that says what it is. Locators in Playwright are lazy (nothing is searched until you act), so creating them up front costs nothing.
📄 pages/login_page.py
from playwright.sync_api import Page
from pages.base_page import BasePage
class LoginPage(BasePage):
path = "#/login"
def __init__(self, page: Page):
super().__init__(page)
self.username = page.get_by_test_id("login-username")
self.password = page.get_by_test_id("login-password")
self.remember_me = page.get_by_test_id("remember-me")
self.submit_button = page.get_by_test_id("login-button")
self.error = page.get_by_test_id("login-error")
def submit(self, username: str, password: str, remember: bool = False):
"""Fill the form and press Log in. Use for negative tests (wrong password, locked user)."""
self.username.fill(username)
self.password.fill(password)
if remember:
self.remember_me.check()
self.submit_button.click()
return self
def login(self, username: str, password: str, remember: bool = False):
"""Log in successfully and return the home page once it is ready."""
self.submit(username, password, remember)
from pages.home_page import HomePage # imported here to avoid a circular import
home = HomePage(self.page)
home.header.account_button.filter(has_text="Hi,").wait_for() # synchronise: the login has finished
return home
login() returns the next page the user lands on. This makes the flow visible in the test and lets your editor autocomplete what you can do next.
Notice the wait_for() line. It is not an assertion; it is synchronisation. While this lesson was being written, a version without it was flaky: after the click, the store switches to its home view a moment later, and a test that searched immediately sometimes had its search results replaced by that home view. A navigation method should return only when the next page is ready, so every test that calls it is safe. Negative tests use submit(), which does not wait for a successful login.
🏠 Step 3: A Component for the Header
The header (search box, account menu, cart badge) appears on every page. Do not copy its locators into each page class; make it a component and attach it to the pages:
📄 pages/components.py
from playwright.sync_api import Page
class Header:
def __init__(self, page: Page):
self.page = page
self.search_input = page.get_by_test_id("search-input")
self.search_button = page.get_by_test_id("search-button")
self.account_button = page.get_by_test_id("account-button")
self.cart_count = page.get_by_test_id("cart-count")
self.cart_link = page.get_by_test_id("cart-link")
def search(self, term: str):
self.search_input.fill(term)
self.search_button.click()
from pages.home_page import SearchResults
return SearchResults(self.page)
def open_cart(self):
self.cart_link.click()
from pages.cart_page import CartPage
return CartPage(self.page)
Now give every page a header through the base class:
📄 pages/base_page.py
from playwright.sync_api import Page
SHOP = "/dummy-ecommerce-website/"
class BasePage:
"""Shared plumbing for all SQA Shop pages."""
path = ""
def __init__(self, page: Page):
self.page = page
from pages.components import Header
self.header = Header(page)
def open(self):
self.page.goto(SHOP + self.path)
return self
🛍️ Step 4: Home, Search Results and Cart
📄 pages/home_page.py
from playwright.sync_api import Locator, Page
from pages.base_page import BasePage
class HomePage(BasePage):
path = "#/"
class SearchResults(BasePage):
def __init__(self, page: Page):
super().__init__(page)
self.cards = page.get_by_test_id("product-card")
def card(self, name: str) -> Locator:
return self.cards.filter(has_text=name).first
def add_to_cart(self, name: str):
self.card(name).get_by_role("button", name="Add to cart").click()
return self
📄 pages/cart_page.py
from playwright.sync_api import Page
from pages.base_page import BasePage
class CartPage(BasePage):
path = "#/cart"
def __init__(self, page: Page):
super().__init__(page)
self.item_names = page.get_by_test_id("cart-item-name")
self.coupon_input = page.get_by_test_id("coupon-input")
self.apply_coupon_button = page.get_by_test_id("apply-coupon")
self.coupon_message = page.get_by_test_id("coupon-message")
self.coupon_discount = page.get_by_test_id("coupon-discount")
self.total = page.get_by_test_id("order-total")
def apply_coupon(self, code: str):
self.coupon_input.fill(code)
self.apply_coupon_button.click()
return self
card(name) shows a useful idea: page objects can return locators built from parameters, so tests can target “the Wireless Earbuds card” without knowing how cards are found.
🧪 Step 5: Tests with Page Objects
Expose page objects as fixtures so tests just ask for them:
📄 tests/conftest.py
import pytest
from playwright.sync_api import Page
from pages.cart_page import CartPage
from pages.home_page import HomePage
from pages.login_page import LoginPage
@pytest.fixture
def login_page(page: Page) -> LoginPage:
return LoginPage(page)
@pytest.fixture
def home(page: Page) -> HomePage:
return HomePage(page).open()
@pytest.fixture
def logged_in_home(login_page: LoginPage) -> HomePage:
return login_page.open().login("testuser", "Test@123")
📄 tests/test_with_pom.py
from playwright.sync_api import expect
from pages.login_page import LoginPage
def test_login_and_add_to_cart(logged_in_home):
expect(logged_in_home.header.account_button).to_contain_text("Hi, Test")
results = logged_in_home.header.search("earbuds")
results.add_to_cart("Wireless Earbuds")
expect(results.header.cart_count).to_have_text("1")
def test_coupon(logged_in_home):
logged_in_home.header.search("earbuds").add_to_cart("Wireless Earbuds")
cart = logged_in_home.header.open_cart()
cart.apply_coupon("SAVE10")
expect(cart.coupon_message).to_have_text("Coupon SAVE10 applied.")
expect(cart.coupon_discount).to_have_text("−₹500")
def test_locked_user_sees_error(login_page: LoginPage):
login_page.open().submit("lockeduser", "Test@123")
expect(login_page.error).to_have_text("This account is locked. Please contact support.")
⌨️ Terminal
pytest tests/test_with_pom.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 3 items
tests/test_with_pom.py::test_login_and_add_to_cart[chromium] PASSED [ 33%]
tests/test_with_pom.py::test_coupon[chromium] PASSED [ 66%]
tests/test_with_pom.py::test_locked_user_sees_error[chromium] PASSED [100%]
============================== 3 passed in 5.45s ==============================
Compare test_coupon with the version at the top: the test now says what happens (log in, search, add, open cart, apply coupon) and the page objects know how.
Your project now looks like this:
project/
├── pages/
│ ├── base_page.py BasePage (+ header for every page)
│ ├── components.py Header
│ ├── login_page.py LoginPage
│ ├── home_page.py HomePage, SearchResults
│ └── cart_page.py CartPage
├── tests/
│ ├── conftest.py page-object fixtures
│ └── test_with_pom.py
└── pytest.ini
✅ Where Do Assertions Go?
Two schools exist. The rule that scales best:
- Page objects expose locators and actions; they do not decide whether a test passes.
- Tests make the assertions with
expect(...)on the page object’s locators.
This keeps page objects reusable: submit() serves the locked-user test, login() the happy paths, and each test states its own expectation. (Waiting for the next page inside login() is synchronisation, not a test verdict.) If you have checks that many tests repeat, add a small, clearly named helper that wraps expect:
📄 pages/assertions.py
from playwright.sync_api import expect
from pages.base_page import BasePage
def expect_logged_in_as(page_object: BasePage, first_name: str):
expect(page_object.header.account_button).to_contain_text(f"Hi, {first_name}")
📄 tests/test_helpers.py
from pages.assertions import expect_logged_in_as
def test_greeting(logged_in_home):
expect_logged_in_as(logged_in_home, "Test")
⌨️ Terminal
pytest -q
🖥️ Output
...... [100%]
6 passed in 12.18s
⚠️ Common POM Mistakes
| Mistake | Why it hurts | Instead |
|---|---|---|
| A “god” page class with every locator of the app | Hard to find anything, merge conflicts | One class per page or view, components for shared parts |
time.sleep() or manual waits inside page methods |
Slow and flaky | Rely on auto-waiting actions and expect in tests |
Returning raw strings like get_text() everywhere |
Loses Playwright’s retrying assertions | Expose locators; assert with expect |
| Page objects that open the browser or read config | Hidden dependencies, hard to test | Pass in the Page; let fixtures handle setup |
Deep inheritance trees (BasePage > ShopPage > CheckoutPage > ...) |
Changes ripple unpredictably | Keep a thin base class; prefer composition (components) |
| Locators as long CSS/XPath strings | Brittle | get_by_role, get_by_label, get_by_test_id (Module 4) |
💡 Tip: Name methods after user intent (apply_coupon, add_to_cart), not after UI mechanics (click_apply_button). When the UI changes from a button to pressing Enter, the method body changes and the tests do not.
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Add a ProductPage class for the product detail view (#/p/<id>), with an open_product(product_id) method, a locator for the title and an add_to_cart() action. The title has the test id pdp-title and the button pdp-add-to-cart.
Show answer
class ProductPage(BasePage):
def __init__(self, page: Page):
super().__init__(page)
self.title = page.get_by_test_id("pdp-title")
self.add_button = page.get_by_test_id("pdp-add-to-cart")
def open_product(self, product_id: str):
self.page.goto(SHOP + f"#/p/{product_id}")
return self
def add_to_cart(self):
self.add_button.click()
return selfUse it as ProductPage(page).open_product("EL-013").add_to_cart(). The product page also has pdp-price, pdp-qty and pdp-buy-now if you want to extend it.
Exercise 2: A teammate wrote def get_cart_count(self) -> str: return self.cart_count.inner_text() and tests do assert header.get_cart_count() == "1". Why is this flaky, and what is better?
Show answer
inner_text() reads the value once, immediately; if the badge updates a moment later the assertion fails. Expose the locator and assert with a retrying assertion: expect(header.cart_count).to_have_text("1").
Exercise 3: Write a fixture cart_with_earbuds that returns a CartPage with Wireless Earbuds already added, using the page objects from the lesson.
Show answer
@pytest.fixture
def cart_with_earbuds(home: HomePage) -> CartPage:
home.header.search("earbuds").add_to_cart("Wireless Earbuds")
return home.header.open_cart()Fixtures that return page objects in a known state make tests very short: def test_flat200(cart_with_earbuds): ....
Exercise 4: Why does LoginPage.login() return a HomePage instead of None, and why does it wait for the greeting before returning?
Show answer
Returning HomePage documents the navigation, lets tests chain calls (LoginPage(page).open().login(...).header.search(...)), and gives editors type information. Waiting for the greeting makes sure the app has finished its own navigation before the test continues; without it, a fast next step can race with the app’s re-render and become flaky.
🧠 MCQ Quiz: Page Object Model in Python
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What problem does the Page Object Model mainly solve?Answer: Locators and page logic duplicated across many tests. POM puts each page’s locators and actions in one class, so a UI change is fixed in one place.
- Where should a page object’s locators be defined?Answer: Once, typically in
__init__, with descriptive names. Defining them once keeps a single source of truth; Playwright locators are lazy, so this is cheap. - Why is creating locators in
__init__cheap in Playwright?Answer: Locators are lazy and only query the page when an action or assertion runs. A Locator is a description; resolution happens at action time, with auto-waiting. - What should
LoginPage.login()return?Answer: The page object for the page the user lands on, such asHomePage. Returning the next page documents the flow and enables chaining and autocompletion. - In the recommended style, where do assertions live?Answer: In tests, using
expecton the page objects’ locators. Page objects stay reusable for positive and negative tests when they do not decide pass or fail. - How should a header that appears on every page be modelled?Answer: As a component class that pages contain. Composition keeps shared UI in one class and avoids deep inheritance.
- Which is a POM anti-pattern?Answer:
time.sleep()inside page methods. Fixed sleeps make tests slow and flaky; Playwright already waits for actionability. - What does a fixture like
logged_in_homegive tests?Answer: A page object already in a known state, keeping tests short. Fixtures that prepare state and return page objects remove setup code from tests. - Why import
HomePageinsidelogin()in the lesson?Answer: To avoid a circular import between modules that reference each other.home_pageimportsbase_page, which importscomponents, which references pages; a local import breaks the cycle. - Which method name is better in a page object?Answer:
apply_coupon(code). Intent-based names survive UI changes and make tests read like requirements.
Want a longer, timed test? Take the Module 10 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 Should a page object have a method for every element?
No. Expose locators as attributes and add methods only for meaningful actions (log in, search, apply coupon). Tests can still act on a locator directly when a one-off interaction is clearer.
🤔 Can I use POM with single-page apps like SQA Shop?
Yes. Treat each view (login, search results, cart, checkout) as a “page” even though the URL only changes after the #. What matters is a class per screen the user sees.
🤔 How do I handle elements that appear on some pages only, like a cookie banner?
Make it a component with its own class (for example CookieBanner) and create it where it can appear, or handle it once in a fixture with page.add_locator_handler() so it never blocks a test.
🤔 Should page objects use dataclasses or properties?
Plain attributes set in __init__ are simplest. Use @property when a locator depends on state (for example the current user), and parameterised methods like card(name) for dynamic elements.
🤔 What comes after POM in a framework?
A clear folder structure (next lesson), design patterns such as factories and builders for test data (Lesson 58), and a complete framework with config, API clients and reporting (Lesson 60).
🏁 Summary
- Page objects give each page or view one class with its locators and actions, removing duplication from tests.
- Define locators once in
__init__; name actions after user intent; return the next page object. - Model shared UI (header, menus, dialogs) as components and keep the base class thin.
- Keep assertions in tests with
expect, plus small named helpers for repeated checks. - Hand page objects to tests through fixtures, and avoid sleeps, god classes and raw-string getters.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page