Playwright interview questions: answers with real output
The test automation questions QA and SDET roles get, answered in plain words, with scripts that drove a real browser against a small sample app.
Playwright interviews test how you write reliable browser tests: role-based locators and strictness, auto-waiting, retrying expect() assertions, browser contexts and isolation, mocking and blocking network calls, waiting for responses, dialogs and iframes, page objects, reusing login state, tracing for CI failures and the sync versus async API. Below are 14 questions; 13 scripts were run with Playwright for Python against the sample app, and the output shown is real.
The small app and helpers every example uses
A minimal job board: a sign-in form, a list loaded from an API after a short delay, a button that is disabled for one second, two Apply buttons, an iframe and a confirm dialog. A route handler serves it from https://app.test/ inside the browser context, so the examples never touch a real site.
import json, os, time
from playwright.sync_api import sync_playwright, expect
APP = """<!doctype html><html><head><title>Job board</title></head><body>
<h1>Job board</h1>
<form id="login"><label>Email <input name="email"></label> <label>Password <input name="password" type="password"></label> <button>Sign in</button></form>
<p id="welcome"></p>
<button id="load">Load jobs</button> <p id="msg"></p> <ul id="jobs"></ul>
<button id="save" disabled>Save search</button>
<div class="card">Data Analyst <button>Apply</button></div> <div class="card">QA Engineer <button>Apply</button></div>
<iframe title="Newsletter" srcdoc="<button onclick="this.textContent='Subscribed'">Subscribe</button>"></iframe>
<button id="delete">Delete account</button> <p id="deleted"></p>
<script>
const $ = id => document.getElementById(id);
$("login").onsubmit = e => { e.preventDefault(); const u = e.target.email.value; localStorage.setItem("user", u); $("welcome").textContent = "Welcome, " + u; };
if (localStorage.getItem("user")) $("welcome").textContent = "Welcome back, " + localStorage.getItem("user");
$("load").onclick = async () => {
$("msg").textContent = "Loading...";
try { const jobs = await (await fetch("/api/jobs")).json();
setTimeout(() => { $("jobs").replaceChildren(...jobs.map(j => Object.assign(document.createElement("li"), {textContent: j})));
$("msg").textContent = jobs.length + (jobs.length === 1 ? " job" : " jobs"); }, 300); }
catch (err) { $("msg").textContent = "Could not load jobs"; } };
setTimeout(() => { $("save").disabled = false; }, 1000);
$("save").onclick = () => { $("save").textContent = "Saved"; };
document.querySelectorAll(".card button").forEach(b => b.onclick = () => { b.textContent = "Applied"; });
$("delete").onclick = () => { $("deleted").textContent = confirm("Delete your account?") ? "Account deleted" : "Account kept"; };
</script></body></html>"""
def serve(route):
if route.request.url.endswith("/api/jobs"): route.fulfill(json=["Data Analyst", "QA Engineer"])
else: route.fulfill(body=APP, content_type="text/html")
def start(pw):
return pw.chromium.launch(channel="chrome")
def app(browser, **context_options):
context = browser.new_context(**context_options)
context.route("https://app.test/**", serve)
page = context.new_page(); page.goto("https://app.test/")
return context, pageBasic Playwright interview questions
Basic1. What is a locator, and which locators should you prefer?
A locator is a description of how to find an element, resolved fresh each time you act on it, so it keeps working when the page re-renders. Prefer locators based on what a user sees and on accessibility: get_by_role with an accessible name, get_by_label for form fields, get_by_text. CSS and XPath selectors tied to layout or generated class names break more easily.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
page.get_by_label("Email").fill("ava@example.com")
page.get_by_label("Password").fill("example-only")
page.get_by_role("button", name="Sign in").click()
print(page.locator("#welcome").text_content())
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)Welcome, ava@example.com
Checked against: Playwright for Python docs: locators
Basic2. What is auto-waiting?
Before an action such as click, Playwright waits until the locator resolves to exactly one element and that element is visible, stable (not animating), able to receive events (not covered by another element), enabled and not inert. In the sample app the Save button is disabled for one second after load; click() simply waits for it instead of failing, so the test needs no sleep.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
save = page.get_by_role("button", name="Save search")
print("enabled right after load:", save.is_enabled())
t = time.monotonic(); save.click()
print("click waited for it:", time.monotonic() - t > 0.5, "| button now reads:", page.locator("#save").text_content())
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)enabled right after load: False click waited for it: True | button now reads: Saved
Checked against: Playwright for Python docs: auto-waiting
Basic3. Why use expect() assertions instead of a plain assert?
expect(locator) assertions retry until the condition holds or the timeout passes (5 seconds by default), which matches how pages update asynchronously. A plain assert on text_content() checks once, at whatever moment it runs. Here the jobs list takes about 300 ms to render: reading immediately sees Loading..., while expect waits for the final state.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
page.get_by_role("button", name="Load jobs").click()
print("read immediately:", page.locator("#msg").text_content())
expect(page.locator("#msg")).to_have_text("2 jobs")
expect(page.get_by_role("listitem")).to_have_count(2)
print("after expect:", page.locator("#msg").text_content(), page.get_by_role("listitem").all_text_contents())
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)read immediately: Loading... after expect: 2 jobs ['Data Analyst', 'QA Engineer']
Checked against: Playwright for Python docs: assertions
Intermediate Playwright interview questions
Intermediate4. What happens when a locator matches more than one element?
Locators are strict: an action that needs one element throws a strict mode violation if several match. That is a feature, because clicking whichever element came first would hide bugs. Narrow the locator instead, for example by filtering a container by its text, rather than reaching for .first.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
try:
page.get_by_role("button", name="Apply").click(timeout=2000)
except Exception as e:
print(str(e).splitlines()[0])
card = page.locator(".card").filter(has_text="QA Engineer")
card.get_by_role("button", name="Apply").click()
print([c.inner_text() for c in page.locator(".card").all()])
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)Locator.click: Error: strict mode violation: get_by_role("button", name="Apply") resolved to 2 elements:
['Data Analyst Apply', 'QA Engineer Applied']Checked against: Playwright for Python docs: locators
Intermediate5. What is a browser context, and why does each test get its own?
A browser context is an isolated session inside one browser, like a fresh profile: its own cookies, local storage and cache. Creating one is cheap, so each test can start clean without launching a new browser, and tests cannot leak state into each other. Pages opened in the same context share that state.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw)
first, page = app(browser)
page.get_by_label("Email").fill("ava@example.com"); page.get_by_role("button", name="Sign in").click()
second_tab = first.new_page(); second_tab.goto("https://app.test/")
other, fresh = app(browser)
print("same context, new tab:", repr(second_tab.locator("#welcome").text_content()))
print("new context: ", repr(fresh.locator("#welcome").text_content()))
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)same context, new tab: 'Welcome back, ava@example.com' new context: ''
Checked against: Playwright for Python docs: isolation
Intermediate6. How do you mock or block API calls?
Register a route for the URL pattern and decide what happens: fulfill with your own response, abort to simulate a network failure, or continue the request with changes. This makes tests fast and lets you test states that are hard to produce against a real backend, such as an error page. In the example, the page-level handlers take over from the sample app's context-level one, and the second route, registered last, is the one that answers the second click.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
page.route("**/api/jobs", lambda route: route.fulfill(json=["Mocked: Staff Engineer"]))
page.get_by_role("button", name="Load jobs").click()
expect(page.locator("#msg")).to_have_text("1 job")
print("mocked:", page.get_by_role("listitem").all_text_contents())
page.route("**/api/jobs", lambda route: route.abort())
page.get_by_role("button", name="Load jobs").click()
expect(page.locator("#msg")).to_have_text("Could not load jobs")
print("aborted:", page.locator("#msg").text_content())
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)mocked: ['Mocked: Staff Engineer'] aborted: Could not load jobs
Checked against: Playwright for Python docs: network
Intermediate7. How do you wait for a network response triggered by a click?
Wrap the action in expect_response with a URL pattern: Playwright starts listening before the click, so the response cannot slip past, and you get the response object to check its status and body. It is more reliable than sleeping and more precise than waiting for network idle.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
with page.expect_response("**/api/jobs") as info:
page.get_by_role("button", name="Load jobs").click()
response = info.value
print(response.status, response.url, response.json())
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)200 https://app.test/api/jobs ['Data Analyst', 'QA Engineer']
Checked against: Playwright for Python docs: network
Intermediate8. How does Playwright handle alert, confirm and prompt dialogs?
By default Playwright dismisses them, so a confirm() returns false and the test carries on. To accept a dialog or check its message, register a handler before the action that opens it. The example clicks Delete account twice: first with no handler, then with one that accepts.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
page.get_by_role("button", name="Delete account").click()
print("no handler:", page.locator("#deleted").text_content())
page.on("dialog", lambda d: (print("dialog:", d.type, "-", d.message), d.accept()))
page.get_by_role("button", name="Delete account").click()
print("with handler:", page.locator("#deleted").text_content())
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)no handler: Account kept dialog: confirm - Delete your account? with handler: Account deleted
Checked against: Playwright for Python docs: dialogs
Intermediate9. How do you work with iframes?
Locators on the page do not reach inside an iframe. Use frame_locator (or locator(...).content_frame) to scope into the frame, then locate as usual; auto-waiting and assertions work the same inside it.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
print("from the page:", page.get_by_role("button", name="Subscribe").count())
frame = page.frame_locator("iframe[title=Newsletter]")
frame.get_by_role("button", name="Subscribe").click()
print("inside the frame:", frame.get_by_role("button").text_content())
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)from the page: 0 inside the frame: Subscribed
Checked against: Playwright for Python docs: frames
Advanced Playwright interview questions
Advanced10. What is the Page Object Model, and how would you write one?
A page object wraps one page or component: it holds its locators and exposes actions in the language of the app (login, search), so tests read as steps and a changed selector is fixed in one place. Keep assertions in the tests, or offer narrow helpers, so page objects do not hide what a test checks.
Python (Playwright)class LoginPage:
def __init__(self, page):
self.page = page
self.email = page.get_by_label("Email")
self.password = page.get_by_label("Password")
self.submit = page.get_by_role("button", name="Sign in")
self.welcome = page.locator("#welcome")
def login(self, email, password):
self.email.fill(email); self.password.fill(password); self.submit.click()
with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
login = LoginPage(page); login.login("ben@example.com", "example-only")
expect(login.welcome).to_have_text("Welcome, ben@example.com")
print("assertion passed:", login.welcome.text_content())
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)assertion passed: Welcome, ben@example.com
Checked against: Playwright for Python docs: page object models
Advanced11. How do you avoid logging in at the start of every test?
Log in once, save the context's storage state (cookies and local storage) to a file, and create later contexts from that file so they start signed in. Treat the file as a secret: it can contain session cookies, so keep it out of version control.
Python (Playwright)with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
page.get_by_label("Email").fill("ava@example.com"); page.get_by_role("button", name="Sign in").click()
context.storage_state(path="state.json")
print("saved:", json.load(open("state.json"))["origins"][0]["localStorage"])
reused, page2 = app(browser, storage_state="state.json")
print("new context:", page2.locator("#welcome").text_content())
browser.close()Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)saved: [{'name': 'user', 'value': 'ava@example.com'}]
new context: Welcome back, ava@example.comChecked against: Playwright for Python docs: authentication
Advanced12. How do you debug a test that fails only in CI?
Record a trace in CI (for example only on retries or failures) and open it in the Trace Viewer: it shows each action, DOM snapshots before and after, console messages and network requests. Then look for the usual causes of flaky tests: fixed sleeps, assertions that do not retry, shared state between tests and dependence on test order or real backends.
Python (Playwright)import zipfile
with sync_playwright() as pw:
browser = start(pw); context, page = app(browser)
context.tracing.start(screenshots=True, snapshots=True)
page.get_by_role("button", name="Load jobs").click()
expect(page.locator("#msg")).to_have_text("2 jobs")
context.tracing.stop(path="trace.zip")
browser.close()
names = zipfile.ZipFile("trace.zip").namelist()
print("trace.zip written:", os.path.getsize("trace.zip") > 0, "| contains a .trace file:", any(n.endswith(".trace") for n in names))Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)trace.zip written: True | contains a .trace file: True
Checked against: Playwright for Python docs: Trace Viewer
Advanced13. When do you use the async API instead of the sync API?
Use the sync API for ordinary scripts and pytest tests; use the async API when your code already runs on asyncio, for example inside an async web service or when you drive several pages concurrently. The calls are the same, with await. The example opens two pages at once with asyncio.gather.
Python (Playwright)import asyncio
from playwright.async_api import async_playwright
async def aserve(route):
if route.request.url.endswith("/api/jobs"): await route.fulfill(json=["Data Analyst", "QA Engineer"])
else: await route.fulfill(body=APP, content_type="text/html")
async def main():
async with async_playwright() as pw:
browser = await pw.chromium.launch(channel="chrome")
context = await browser.new_context(); await context.route("https://app.test/**", aserve)
pages = [await context.new_page() for _ in range(2)]
await asyncio.gather(*(p.goto("https://app.test/") for p in pages))
print([await p.title() for p in pages])
await browser.close()
asyncio.run(main())Output (Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless)['Job board', 'Job board']
Checked against: Playwright for Python docs: library
Advanced14. Which browsers does Playwright support, and what does headless mean?
Playwright drives Chromium, Firefox and WebKit, and branded Chrome or Edge through the channel option (the examples here use the installed Google Chrome). Headless means the browser runs without a visible window, which is the usual mode in CI; headed mode helps while you write or debug a test. Run your key tests on all three engines, because layout and timing can differ between them.
Checked against: Playwright for Python docs: browsers
How to practice with this page
- Explain why each locator and assertion is robust, not just what it does.
- Re-run an example with a plain sleep instead of an assertion and note what breaks.
- Practice in the language the team uses: the TypeScript API has the same concepts with camelCase names.
- Prepare a story about a flaky test you fixed and how you found the cause.
Related interview prep and tools
The language many Playwright suites use.
Open →QuestionsPython interview questionsCore language questions with real output.
Open →QuestionsTypeScript interview questionsTypes and runtime behavior, with real output.
Open →RoleQA tester interview questionsRole-specific interview questions.
Open →Free toolResume summary generatorDraft a summary for a QA Automation Engineer role; the title is filled in, you add your experience.
Open →Free toolLinkedIn headline generatorWrite a headline for a QA Automation Engineer search.
Open →Disclosure: TryHired makes HIRED, a paid job-search program, so we have a conflict of interest when we mention it. This question bank is free, with no TryHired signup.
Questions people ask
What Playwright topics come up often in interviews?
Do these answers apply to Playwright with TypeScript or JavaScript?
How should I prepare for a hands-on Playwright exercise?
How this page is built
TryHired wrote these questions and answers. Every script on this page was run with Playwright 1.63.0 for Python, Google Chrome 157.0.8103.40 headless when the page was built (2026-11-15), against the sample app shown above, which a route handler serves inside the browser context, so no request left the build machine. Timing-dependent results are printed as true or false. The output shown is the real output, and the build stops if any example fails. The question list is general practice: it does not predict what a particular employer will ask.
- Interviewers ask different questions for different roles and levels.
- Answers are short explanations, not complete references.
- The examples use the Python library with the sync API (and one async example); Playwright Test for JavaScript and TypeScript adds a runner with fixtures, retries and parallel workers that is not shown here.
- Playwright for Python docs: auto-waiting (read 2026-11-15)
- Playwright for Python docs: assertions (read 2026-11-15)
- Playwright for Python docs: authentication (read 2026-11-15)
- Playwright for Python docs: browsers (read 2026-11-15)
- Playwright for Python docs: isolation (read 2026-11-15)
- Playwright for Python docs: dialogs (read 2026-11-15)
- Playwright for Python docs: frames (read 2026-11-15)
- Playwright for Python docs: library (read 2026-11-15)
- Playwright for Python docs: locators (read 2026-11-15)
- Playwright for Python docs: network (read 2026-11-15)
- Playwright for Python docs: page object models (read 2026-11-15)
- Playwright for Python docs: Trace Viewer (read 2026-11-15)