Playwright Trace Viewer for Python Tests (Record, Open, Read)
A screenshot shows the moment of failure. A trace shows the whole story: every action, the page before and after each step, the console, every network request and the line of code that ran. Playwright’s Trace Viewer turns a failed CI run into something you can replay on your laptop, step by step. In this lesson you will record traces with pytest-playwright’s --tracing option and with the context.tracing API, group steps so traces read like a test plan, split long flows into chunks, look inside a trace file, open it with playwright show-trace or trace.playwright.dev, and collect traces as CI artifacts.
📖 What You’ll Learn: what a Playwright trace contains, –tracing on and retain-on-failure, where traces are saved (–output), context.tracing.start and stop with screenshots, snapshots and sources, naming traces with title, tracing.group to label steps, start_chunk and stop_chunk for one trace per phase, the contents of trace.zip, playwright show-trace, trace.playwright.dev, the Trace Viewer tabs, traces in CI, and trace size and privacy.
🎞️ What Is a Trace?
A trace is a trace.zip file recorded while a test runs. Opened in the Trace Viewer, it shows:
| Part | What you see |
|---|---|
| Actions | Every Playwright call (goto, click, fill, expect …) with its duration |
| Snapshots | The DOM before, during and after each action, which you can inspect like a live page |
| Timeline | A filmstrip of screenshots across the whole test |
| Console | Messages and errors the page logged |
| Network | Every request and response, with headers and bodies |
| Source | The line of your test that triggered each action |
| Errors | The failure message and call log, attached to the failing step |
It is the single most useful artifact for a test that fails in CI but not on your machine.
⚡ Record Traces with –tracing
pytest-playwright records traces for you:
| Option | Traces kept |
|---|---|
--tracing on |
For every test |
--tracing retain-on-failure |
Only for failed tests (recommended for CI) |
--tracing off |
None (default) |
📄 pytest.ini
[pytest]
addopts = --base-url https://sqatools.in
📄 tests/test_cart.py
from playwright.sync_api import Page, expect
SHOP = "/dummy-ecommerce-website/"
def test_add_earbuds(page: Page):
page.goto(SHOP + "#/search/earbuds")
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_wrong_expectation(page: Page):
page.goto(SHOP + "#/search/earbuds")
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-discount")).to_have_text("−₹400", timeout=3_000) # real value: −₹500
⌨️ Terminal
pytest --tracing retain-on-failure -q --tb=line
🖥️ Output
.F [100%]
================================== FAILURES ===================================
E AssertionError: Locator expected to have text '−₹400'
Actual value: −₹500
Call log:
- Expect "to_have_text" get_by_test_id("coupon-discount") with timeout 3000ms
- waiting for get_by_test_id("coupon-discount")
10 × locator resolved to <dd class="save" data-testid="coupon-discount">−₹500</dd>
- unexpected value "−₹500"
Aria snapshot:
- definition: −₹500
C:\Users\you\playwright-python\tests\test_cart.py:18: AssertionError: Locator expected to have text '−₹400'
=========================== short test summary info ===========================
FAILED tests/test_cart.py::test_coupon_wrong_expectation[chromium] - Assertio...
1 failed, 1 passed in 7.94s
📄 list_results.py
from pathlib import Path
for path in sorted(Path("test-results").rglob("*.zip")):
print(path.as_posix(), f"{path.stat().st_size // 1024} KB")
⌨️ Terminal
python list_results.py
🖥️ Output
test-results/tests-test-cart-py-test-coupon-wrong-expectation-chromium/trace.zip 1233 KB
Only the failed test kept a trace, in a folder named after the test inside test-results/ (change the folder with --output). Combine it with --screenshot only-on-failure and --video retain-on-failure for the full set of failure artifacts.
🔍 Open the Trace
⌨️ Terminal
playwright show-trace test-results/tests-test-cart-py-test-coupon-wrong-expectation-chromium/trace.zip
The Trace Viewer opens in a window. Alternatively, drag the zip onto https://trace.playwright.dev: the page loads the viewer, but the trace is processed locally in your browser and is not uploaded.
How to read it for this failure:
- In the actions list on the left, the last item,
expect.to_have_text, is red. - Click it: the Call tab shows the expected
−₹400and the received−₹500. - The After snapshot shows the cart with the discount line; hover elements to see their locators.
- The Network tab shows that no request failed, so the app behaved; the expectation was wrong.
Thirty seconds, and you know whether to fix the test or file a bug.
🧾 What Is Inside trace.zip?
A trace is an ordinary zip file. Looking inside once makes it far less mysterious:
📄 inspect_trace.py
import json
import zipfile
from collections import Counter
from pathlib import Path
trace = next(Path("test-results").rglob("trace.zip"))
with zipfile.ZipFile(trace) as z:
names = z.namelist()
print("contents:", dict(Counter(n.split("/")[0] + ("/" if "/" in n else "") for n in names)))
events = [json.loads(line) for line in z.read("trace.trace").decode("utf-8").splitlines() if line.strip()]
for e in events:
if e.get("type") == "before" and e.get("class") in ("Frame", "Page", "Locator") or e.get("method") == "expect":
params = e.get("params", {})
print(f"{e.get('method'):12} {params.get('selector', params.get('url', ''))[:70]}")
⌨️ Terminal
python inspect_trace.py
🖥️ Output
contents: {'trace.trace': 1, 'trace.network': 1, 'screencast/': 29, 'resources/': 22, 'trace.stacks': 1, 'src/': 1}
goto /dummy-ecommerce-website/#/search/earbuds
click internal:role=button[name="Add to cart"i] >> nth=0
goto /dummy-ecommerce-website/#/cart
fill internal:testid=[data-testid="coupon-input"s]
click internal:testid=[data-testid="apply-coupon"s]
expect internal:testid=[data-testid="coupon-discount"s]
trace.trace holds the actions as JSON lines, trace.network the HTTP traffic, resources/ the snapshots and response bodies, screencast/ the filmstrip frames and src/ your test’s source code. The action list also shows how Playwright stores locators internally: get_by_role("button", name="Add to cart") becomes internal:role=button[name="Add to cart"i], where the trailing i means case-insensitive matching. You never need to read these by hand, but it explains why traces can contain sensitive data: everything the page sent and received is in there.
🎛️ Record Traces Yourself: context.tracing
Outside pytest-playwright (scripts, custom fixtures) or when you need more control, use the tracing API on a browser context:
📄 manual_trace.py
from playwright.sync_api import expect, sync_playwright
SHOP = "https://sqatools.in/dummy-ecommerce-website/"
with sync_playwright() as p:
browser = p.chromium.launch()
context = browser.new_context()
context.tracing.start(screenshots=True, snapshots=True, sources=True, title="Checkout as guest")
page = context.new_page()
with context.tracing.group("Find and add the earbuds"):
page.goto(SHOP + "#/search/earbuds")
page.get_by_role("button", name="Add to cart").first.click()
expect(page.get_by_test_id("cart-count")).to_have_text("1")
with context.tracing.group("Apply a coupon"):
page.goto(SHOP + "#/cart")
page.get_by_test_id("coupon-input").fill("FLAT200")
page.get_by_test_id("apply-coupon").click()
expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹200")
context.tracing.stop(path="traces/guest-checkout.zip")
browser.close()
print("saved traces/guest-checkout.zip")
⌨️ Terminal
python manual_trace.py
🖥️ Output
saved traces/guest-checkout.zip
screenshots=Truebuilds the filmstrip,snapshots=Truerecords DOM snapshots and network,sources=Trueembeds your source code so the viewer can show it.titlenames the trace in the viewer.tracing.group(...)(usable as awithblock) collapses the actions under a readable heading, so a long trace reads like a test plan.
✂️ One Trace per Phase: Chunks
For a long flow you may want separate traces for each phase, without restarting tracing. start_chunk() / stop_chunk(path=...) cut the recording into pieces:
📄 chunks.py
from playwright.sync_api import sync_playwright
SHOP = "https://sqatools.in/dummy-ecommerce-website/"
with sync_playwright() as p:
browser = p.chromium.launch()
context = browser.new_context()
context.tracing.start(screenshots=True, snapshots=True)
page = context.new_page()
context.tracing.start_chunk(title="login")
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("account-button").filter(has_text="Hi,").wait_for()
context.tracing.stop_chunk(path="traces/1-login.zip")
context.tracing.start_chunk(title="search")
page.get_by_test_id("search-input").fill("course")
page.get_by_test_id("search-button").click()
page.get_by_test_id("product-card").first.wait_for()
context.tracing.stop_chunk(path="traces/2-search.zip")
context.tracing.stop()
browser.close()
from pathlib import Path
for f in sorted(Path("traces").glob("*.zip")):
print(f.name, f"{f.stat().st_size // 1024} KB")
⌨️ Terminal
python chunks.py
🖥️ Output
1-login.zip 826 KB
2-search.zip 472 KB
guest-checkout.zip 829 KB
Chunks are handy for monitoring scripts and for very long tests where one giant trace would be slow to open.
🏭 Traces in CI
In a pipeline, record traces only for failures and upload the results folder as a build artifact:
- name: Run tests
run: pytest --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure
- name: Upload failure artifacts
if: failure()
uses: actions/upload-artifact@v4
with:
name: playwright-test-results
path: test-results/
retention-days: 7
Download the artifact from the failed run, unzip it, and open the trace with playwright show-trace (Lesson 66 builds the full workflow). Combine with retries (Lesson 44): with pytest-rerunfailures, each failed attempt keeps its own trace, so you can compare a failing and a passing attempt of a flaky test.
🔐 Size and Privacy
- A trace for a short test is typically 0.5 to 3 MB; long tests with many screenshots can reach tens of MB.
retain-on-failurekeeps storage small. - Traces contain everything: page content, form values, cookies and API bodies. Use test accounts and test data, restrict who can download CI artifacts, and set a short retention period.
🏋️ 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: Write the pytest command that keeps a trace, a screenshot and a video only for failed tests, and stores them in a folder called artifacts.
Show answer
pytest --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure --output artifactsExercise 2: Write a fixture that records a trace for every test manually (instead of --tracing) and saves it as traces/<test name>.zip only when the test failed.
Show answer
import pytest
@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
report = yield
if report.when == "call":
item.failed_call = report.failed
return report
@pytest.fixture
def traced_page(context, request):
context.tracing.start(screenshots=True, snapshots=True, sources=True)
page = context.new_page()
yield page
if getattr(request.node, "failed_call", False):
context.tracing.stop(path=f"traces/{request.node.name}.zip")
else:
context.tracing.stop()The hook (in conftest.py) records whether the test body failed; the fixture saves the trace only then. pytest-playwright’s --tracing retain-on-failure does exactly this for you, so prefer it unless you need custom names.
Exercise 3: In the Trace Viewer, how do you find out whether a failure was caused by a slow API or by a wrong locator?
Show answer
Select the failing action. If its call log shows the element was never found, check the After snapshot for the element (wrong locator or changed UI). Then open the Network tab around that time: a request still pending or a 500 response points to the backend, while all requests finishing normally points to the locator or expectation.
Exercise 4: Group the steps of the SQA Shop login in a manual trace under the heading “Log in as testuser”.
Show answer
with context.tracing.group("Log in as testuser"):
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()Without with, call context.tracing.group("...") and later context.tracing.group_end().
🧠 MCQ Quiz: Trace Viewer for Python Tests
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which option keeps traces only for failing tests?Answer:
--tracing retain-on-failure.retain-on-failurerecords every test but deletes traces of passing ones. - Where does pytest-playwright save traces by default?Answer: In
test-results/, one folder per test. Artifacts go totest-results/unless--outputsays otherwise. - How do you open a trace on your machine?Answer:
playwright show-trace path/to/trace.zip. The Playwright CLI includes the Trace Viewer. - Is a trace uploaded to a server when you open it at trace.playwright.dev?Answer: No, it is processed locally in your browser. The web viewer runs entirely client-side.
- What does
snapshots=Trueadd intracing.start()?Answer: DOM snapshots for each action and network activity. Snapshots let you inspect the page before and after each action. - What does
context.tracing.group("Apply a coupon")do?Answer: Groups the following actions under that heading in the viewer. Groups make long traces readable; end them withgroup_end()or awithblock. - What are
start_chunk()andstop_chunk(path=...)for?Answer: Saving separate trace files for phases without restarting tracing. Chunks cut one tracing session into several zip files. - Which Trace Viewer tab tells you if the backend returned an error?Answer: Network. The network tab lists every request with status, headers and body.
- Why must CI trace artifacts be protected?Answer: They contain page content, form values, cookies and API bodies. A trace is a complete recording of what the browser saw and sent.
- What does
sources=Trueadd to a trace?Answer: Your test’s source code, shown next to each action. The viewer shows which line of your code triggered each action.
Want a longer, timed test? Take the Module 11 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 Do traces slow tests down?
A little: recording snapshots and screenshots costs some time and disk. retain-on-failure still records every test but deletes passing traces, so most teams accept the small overhead in CI for the debugging value. Locally, turn tracing on only when you need it.
🤔 Do traces include API calls made with page.request?
Yes. Requests made through page.request or context.request appear in the trace alongside UI actions. A separate playwright.request.new_context() is not part of the browser context’s trace.
🤔 Can I share a trace with a developer?
Yes, send the zip (or the CI artifact link). They can open it with playwright show-trace or at trace.playwright.dev without installing anything else. Check it for sensitive data first.
🤔 What is the difference between a trace and a HAR file?
A HAR (Lesson 53) records only network traffic and can be replayed. A trace records actions, DOM snapshots, console and network for debugging. Use traces to investigate failures, HARs to mock APIs.
🤔 Why does my trace not show my assertions?
Assertions made with Playwright’s expect appear as actions in the trace. Plain Python assert statements do not, because they never talk to the browser; their failure shows up as the test’s error instead.
🏁 Summary
- A trace records actions, DOM snapshots, screenshots, console, network and source for a test.
- Use
--tracing retain-on-failure(with screenshots and videos) to keep artifacts only for failures intest-results/. - Open traces with
playwright show-traceor trace.playwright.dev; start from the failing action, then check snapshots and network. context.tracing.start/stoprecords traces manually;group()labels steps andstart_chunk()/stop_chunk()splits phases.- Upload
test-results/as a CI artifact on failure, and treat traces as sensitive data.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page