Playwright Python Interview Questions and Answers (2026)

This page collects the Playwright with Python questions that come up in QA automation and SDET interviews, from fresher level to experienced, with short answers you can say out loud and code where it helps. Every answer links to the lesson where the topic is explained in depth, so you can revise quickly and then go deeper. Use it the night before an interview, and use the module mock interviews to test yourself under time pressure.

Advertisement

📖 What You’ll Learn: how to answer questions on Playwright architecture and the sync and async APIs, browsers, contexts and pages, locators and strict mode, auto-waiting and web-first assertions, pytest-playwright fixtures and options, configuration and test data, authentication and storage state, network mocking and HAR, API testing, page objects and framework design, debugging, traces and reports, parallel runs and CI, plus scenario questions with model answers.


🎯 How to Use This Page

  • Freshers: focus on the Basics, Locators and Waits sections and be ready to write a small test live.
  • 2–5 years: expect framework, fixtures, data, authentication and CI questions, and “how would you test…” scenarios.
  • Senior: expect trade-offs: flakiness strategy, parallelism, hybrid API + UI design, reporting and team practices.

Answer in three parts: what it is, how you use it (one line of code if possible), why it matters. Interviewers listen for the “why”.


🧱 Basics

  1. What is Playwright, and why use it with Python?

Playwright is an open-source browser automation library from Microsoft that drives Chromium, Firefox and WebKit through one API. With Python you combine it with pytest (via pytest-playwright) for fixtures, parametrization and plugins. Key strengths: auto-waiting, web-first assertions, isolated browser contexts, network interception, tracing and fast, reliable execution. (Lesson 1)

  1. What is the difference between the sync and async APIs?

Same classes and methods; the sync API (playwright.sync_api) blocks on each call and is the default for tests, the async API (playwright.async_api) needs await and an asyncio loop and is used inside async applications or for concurrency within one process. pytest-playwright is sync; pytest-playwright-asyncio provides async fixtures. (Lesson 69)

  1. Explain Browser, BrowserContext and Page.

A Browser is a launched browser process. A BrowserContext is an isolated, incognito-like session inside it (own cookies, storage, permissions). A Page is a tab in a context. pytest-playwright launches the browser once per session and creates a fresh context and page for each test, which is why tests are isolated and still fast. (Lesson 41)

  1. Which browsers does Playwright support, and how do you run tests in Firefox?

Chromium (Chrome, Edge), Firefox and WebKit (Safari engine), on Windows, macOS and Linux. pytest --browser firefox; repeat --browser for several; --browser-channel chrome or msedge uses the installed branded browser. (Lesson 49)

  1. How do you install Playwright for Python?

pip install pytest-playwright (installs playwright and pytest), then playwright install to download the browsers (--with-deps on Linux/CI for system libraries). (Lesson 2)

  1. What does Codegen do?

playwright codegen <url> opens a browser and records your actions as Python code with recommended locators. Use it to explore an app and find locators, then refactor the code into proper tests with assertions. (Lesson 7)


🎯 Locators and Actions

  1. Which locators does Playwright recommend, and why?

User-facing ones: get_by_role (with name), get_by_label, get_by_placeholder, get_by_text, get_by_alt_text, get_by_title, and get_by_test_id for stable test hooks. They follow how users and assistive technology see the page and survive markup changes better than CSS or XPath. (Lesson 31)

  1. What is strict mode?

Actions on a locator must match exactly one element; if several match, Playwright raises a “strict mode violation” listing the matches instead of guessing. Fix it by making the locator more specific (filter, exact=True, a parent scope) or by choosing explicitly with .first/.nth() when any match is fine. (Lesson 61)

  1. Is a locator evaluated when you create it?

No. Locators are lazy descriptions; they are resolved each time you act or assert, with auto-waiting. That is why you can define them once in page objects. (Lesson 56)

  1. How do you narrow a locator to one item in a list?

Chain and filter: page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart"). filter(has=...) filters by a child locator, has_not_text excludes.

  1. When would you still use CSS or XPath?

When no user-facing attribute exists and you cannot add a test id, for example legacy markup or complex table structures. Keep them short and anchored to stable attributes, never to auto-generated classes or long absolute paths. (Lesson 32)

  1. fill() vs type() vs press_sequentially()?

fill() sets the value in one step (fast, clears first). press_sequentially() types character by character, firing key events, for inputs with per-key behaviour such as autocomplete. keyboard.type() types at the focused element. (Lesson 33)

  1. How do you handle dialogs, iframes and new tabs?

Dialogs: page.on("dialog", lambda d: d.accept()) before triggering them. Iframes: page.frame_locator("#frame").get_by_role(...) (or locator.content_frame). New tabs: with context.expect_page() as info: click() then info.value. (Lesson 34)

Advertisement

  1. How do you upload and download files?

Upload: locator.set_input_files("file.pdf"). Download: with page.expect_download() as info: click(), then info.value.save_as(path) and read suggested_filename. (Lesson 36)


⏱️ Waits and Assertions

  1. What is auto-waiting?

Before an action Playwright waits until the element is attached, visible, stable, enabled and receives events (actionability checks), up to the timeout. You almost never need manual waits. (Lesson 38)

  1. What are web-first assertions?

expect(locator).to_have_text(...), to_be_visible(), to_have_count() and friends retry until the condition is met or the timeout (5 s default) expires. A plain assert locator.inner_text() == ... reads once and is a common source of flakiness. (Lesson 37)

  1. Why is time.sleep() bad in Playwright tests?

It waits a fixed time: too short on slow runs (flaky) and too long on fast ones (slow suites). Use auto-waiting actions and expect; for special cases wait for an event (expect_response, wait_for_url). (Lesson 44)

  1. How do you change timeouts?

expect(locator).to_be_visible(timeout=10_000) for one assertion, expect.set_options(timeout=...) globally for assertions, page.set_default_timeout() / set_default_navigation_timeout() for actions, or --timeout style options in your fixtures. Raise them only where the app is slow by design.

  1. How do you assert a list of items?

expect(page.get_by_test_id("product")).to_have_text(["A", "B", "C"]) checks count, order and text in one retrying assertion; to_contain_text([...]) checks substrings. (Lesson 55)


🧪 pytest-playwright

  1. Which fixtures does pytest-playwright provide?

playwright, browser_type, browser, browser_name, context, page, new_context, browser_type_launch_args, browser_context_args, connect_options, plus base_url from pytest-base-url. Override browser_context_args to add context options for all tests. (Lesson 41)

  1. Which command-line options do you use most?

--headed, --slowmo, --browser, --browser-channel, --device, --base-url, --tracing, --screenshot, --video, --output. (Lesson 5)

  1. How do you run one test on mobile emulation?

pytest --device "iPhone 15" --browser webkit, or override browser_context_args with playwright.devices["Pixel 7"] for a folder of tests. (Lesson 50)

  1. How do you skip a test for one browser?

@pytest.mark.skip_browser("webkit") or @pytest.mark.only_browser("chromium"), always with a reason in the code review. (Lesson 43)


🗂️ Data, Configuration and Environments

  1. How do you make tests data-driven?

@pytest.mark.parametrize with pytest.param(..., id=...), data from JSON/CSV/Excel loaded once with a helper, or parametrized fixtures for setups such as user roles. (Lessons 45, 46)

  1. How do you keep credentials out of the code?

Environment variables, loaded from a git-ignored .env with python-dotenv locally and from CI secrets in pipelines, collected in one validated settings object with secrets hidden from repr. (Lesson 47)

  1. How do you run the same suite against QA and staging?

Relative page.goto() with base_url, a custom --env option (pytest_addoption) that loads per-environment config, and markers that block destructive tests on read-only environments. (Lesson 48)


🔐 Authentication and Network

  1. How do you avoid logging in through the UI in every test?

Log in once in a session fixture and save context.storage_state(path=...); create each test’s context with storage_state=. Each test is still isolated. Note that sessionStorage is not saved. (Lesson 51)

  1. How do you mock an API response?

page.route("**/api/products*", lambda route: route.fulfill(json={...})) registered before the request. route.abort() simulates network failure; route.fetch() plus fulfill(response=..., json=...) modifies a real response. (Lesson 52)

  1. How do you wait for and inspect a specific request or response?

with page.expect_response("**/api/orders") as info: click() then info.value.json(); for requests expect_request and request.post_data_json.

  1. What is a HAR file and how does Playwright use it?

An HTTP archive of requests and responses. page.route_from_har(path, url=..., update=True) records; without update it replays, so tests get realistic data offline. (Lesson 53)


🔌 API Testing

  1. How do you test APIs with Playwright Python?

playwright.request.new_context(base_url=...) gives an APIRequestContext with get, post, put, patch, delete; check status, json(), headers, or expect(response).to_be_ok(). End the base URL with / and use paths without a leading slash. (Lesson 54)

  1. What is the difference between page.request and a new request context?

page.request shares the browser context’s cookies (log in by API, continue in the UI); a new request context has its own isolated cookie jar. (Lesson 55)


🏗️ Framework Design

  1. How do you structure a Playwright Python framework?

pages/ (page objects and components), api/ (clients), config/ (settings), data/, tests/ split by layer, layered conftest.py files, settings in pyproject.toml with strict markers, pinned requirements. (Lesson 57)

  1. Explain the Page Object Model and one common mistake.

One class per page with locators defined once and intent-named actions that return the next page; tests keep the assertions. Common mistakes: god classes, sleeps inside page methods, returning raw strings instead of locators. (Lesson 56)

Advertisement

  1. Which design patterns do you use besides POM?

Factories for unique valid test data, builders for complex payloads, the factory-as-fixture pattern with clean-up, a facade for user journeys, and strategies for interchangeable login methods. (Lesson 58)

  1. How do you use BDD with Playwright Python?

pytest-bdd: Gherkin feature files bound with scenarios(), steps with @given/@when/@then and parsers.parse, target_fixture to share state, tags as markers. (Lesson 59)


🐞 Debugging, Reporting, CI

  1. How do you debug a failing test?

Read the full error (call log, actual value, aria snapshot), run it alone headed with --slowmo, step through with PWDEBUG=1 or page.pause(), inspect code with --pdb, and open the trace. (Lesson 61)

  1. What is the Trace Viewer?

A recording of actions with DOM snapshots, screenshots, console, network and source. Record with --tracing retain-on-failure, open with playwright show-trace or trace.playwright.dev, or inspect in a terminal with python -m playwright trace. (Lesson 62)

  1. Which reports do you use?

pytest-html for a single shareable file (with screenshots attached by a pytest_runtest_makereport hook), Allure for steps, history and quality gates, JUnit XML for CI dashboards. (Lessons 63, 64)

  1. How do you run tests in parallel?

pytest-xdist: pytest -n auto; each worker has its own browser and session fixtures, so data must be unique per worker and one-time setup needs a file lock. (Lesson 65)

  1. How do you run Playwright Python in CI?

Install pinned requirements, playwright install --with-deps, run pytest with traces on failure and JUnit output, upload test-results/ as an artifact, pass credentials as secrets; or use the mcr.microsoft.com/playwright/python image. (Lessons 66, 68)


💡 Scenario Questions

  1. A test passes locally but fails in CI. How do you investigate?

Get the trace and screenshot from the CI artifacts; compare with a local trace. Typical causes: timing (missing web-first assertion), different viewport or headless behaviour, environment data, missing fonts or locale, parallel runs sharing data, network to third parties. Reproduce with the same browser, --headed off, and -n setting.

  1. Your suite takes 60 minutes. How do you make it faster?

Measure first (--durations). Then: log in once with storage state, create data via API or seeded state instead of UI steps, mock slow third parties, parallelise with xdist and CI sharding, run a smoke subset per commit and the full suite nightly, and delete redundant UI tests that duplicate API coverage.

  1. How do you deal with flaky tests?

Treat flakiness as a bug: find the cause with traces (timing, shared state, test data, environment), fix it with proper waits, isolation or mocks; quarantine with a marker and a ticket while fixing; use retries (pytest-rerunfailures) only as a temporary safety net and track how often they happen. (Lesson 44)

  1. How would you automate a checkout with a payment step?

Use a test payment mode (sandbox cards), seed the cart via API or storage for most tests, cover each payment method and failure (declined card, terms not accepted), verify money as numbers, check side effects (cart emptied, order exists), and keep one full UI journey as a smoke test. (Project 2)


🧑‍💻 A Live-Coding Warm-Up

Interviewers often ask for a small test on the spot. Practise this one until you can type it in two minutes:

📄 tests/test_live.py

from playwright.sync_api import Page, expect


def test_locked_user_sees_error(page: Page):
    page.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-username").fill("lockeduser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_role("button", name="Log in", exact=True).click()
    expect(page.get_by_test_id("login-error")).to_have_text("This account is locked. Please contact support.")

⌨️ Terminal

pytest -q

🖥️ Output

.                                                                        [100%]
1 passed in 3.26s

While typing, say what you do and why: “role locator with an exact name, because ‘Log in’ also appears in the page heading; a web-first assertion, so no sleeps”.


Advertisement

🏋️ 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: Answer in under a minute: “Why are Playwright tests usually less flaky than Selenium tests?”

Show answer

Three built-in reasons: actions auto-wait for elements to be actionable; assertions are web-first and retry until the expected state appears; and each test runs in a fresh browser context, so state does not leak between tests. Flakiness still happens with bad test design (fixed sleeps, shared data, fragile locators), so those rules still apply.

Exercise 2: Write the code that mocks **/api/user to return {"name": "Test", "plan": "pro"} and checks the page shows “Pro plan”.

Show answer
def test_pro_plan_badge(page):
    page.route("**/api/user", lambda route: route.fulfill(json={"name": "Test", "plan": "pro"}))
    page.goto("/account")
    expect(page.get_by_text("Pro plan")).to_be_visible()

The route is registered before goto, so the first request is already intercepted.

Exercise 3: The interviewer asks: “How do you share a logged-in state across 300 tests without making them depend on each other?” Give a structured answer.

Show answer

Log in once per run (per xdist worker) in a session-scoped fixture, assert the login worked, and save context.storage_state() to a git-ignored file. Every test then gets a new context created with that state, so it starts logged in but isolated. Tests that need a guest opt out with a marker. If the app keeps its session in sessionStorage, restore it with an init script.

Exercise 4: Explain, with code, how you would assert that a table has exactly three rows with the texts “Alpha”, “Beta”, “Gamma” in order.

Show answer
expect(page.locator("table#results tbody tr")).to_have_text(["Alpha", "Beta", "Gamma"])

One retrying assertion checks the count, the order and each row’s text (use to_contain_text if rows contain more text).


🧠 MCQ Quiz: Playwright Python Interview Questions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does a BrowserContext provide?
  2. Which locator is generally preferred?
  3. What happens when a locator matches two elements and you call click()?
  4. Why prefer expect(locator).to_have_text() over assert locator.inner_text() ==?
  5. How do you reuse a login across tests?
  6. Which API mocks a network response?
  7. What does page.request share with the browser context?
  8. Which plugin runs Playwright Python tests in parallel?
  9. What is the best first step when a test fails only in CI?
  10. Which is a sound flaky-test strategy?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


Advertisement

❓ Frequently Asked Questions

🤔 How should I prepare for a Playwright Python interview in one week?

Day 1–2: Modules 1, 4 and 5 (setup, locators, assertions). Day 3: fixtures and data (Modules 6, 7). Day 4: auth, network and API (Modules 8, 9). Day 5: framework design (Module 10). Day 6: debugging and CI (Modules 11, 12). Day 7: the mock interviews and one project.

🤔 Do interviewers expect Selenium knowledge too?

Often. Be ready to compare: Playwright’s auto-waiting, contexts, network control and tracing versus Selenium’s WebDriver protocol, explicit waits and wider legacy ecosystem. Explain when you would choose each.

🤔 Will I be asked to write code live?

Frequently: a small test, a page object, a fixture or a parametrized test. Practise the warm-up above and the practice questions of the lessons out loud.

🤔 Where can I test myself with timed questions?

In the Playwright Python mock interviews: 13 module tests with 200-question banks, 20 random questions in 20 minutes each.

🤔 What should I put in my CV?

Concrete outcomes: “Built a Playwright Python + pytest framework with 400 tests running in 12 minutes in GitHub Actions; cut flaky failures by 80% with storage-state logins and API data setup.” Link a public practice repository (for example one of the projects from Module 14).


🏁 Summary

  • Know the building blocks: browsers, contexts, pages, locators, strict mode, auto-waiting and web-first assertions.
  • Be fluent with pytest-playwright fixtures and options, data-driven tests, environments and secrets.
  • Explain storage-state logins, network mocking, HAR and API testing with short code examples.
  • Describe a framework (structure, POM, patterns, BDD) and the debugging, reporting, parallel and CI story.
  • Answer scenario questions with a method: evidence first, root cause, prevention, then speed.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page