The Hard Stuff: Dynamic Elements, iframes, Uploads & Network Stubbing
This is the last 20% of real apps — the tricky bits where beginners get stuck. Good news: four patterns handle almost all of it.
The idea, in one line
Late-appearing elements, iframes, file uploads, and fake network responses each have a clean, built-in answer in Playwright.
The four patterns
- Dynamic elements that appear late need no sleep. A locator plus
expect(...).to_be_visible()auto-retries until the element arrives or times out. - iframes are separate documents. Reach inside with
page.frame_locator("iframe#pay").get_by_role(...)— you chain through the frame instead of using the raw page. - File uploads skip the OS dialog entirely: target the
<input type=file>and calllocator.set_input_files("invoice.pdf"). Pass a list for several files, or[]to clear. - Network stubbing is the superpower — the next section is all about it.
Advanced — faking the network with page.route
With page.route(pattern, handler) you intercept a request and answer it yourself using route.fulfill(json=...). Return a fixed catalog, force a 500 to test your error screen, or route.abort() to pretend the backend is dead.
See it work
▸ try it
from playwright.sync_api import Page, Route, expect
def test_error_banner_on_500(page: Page):
# Force the products API to fail, then check the UI copes
def fail(route: Route):
route.fulfill(status=500, json={"error": "down"})
page.route("**/api/v1/products", fail)
page.goto("https://demo.playwright.dev/api-mocking")
expect(page.get_by_text("Something went wrong")).to_be_visible()
def test_upload(page: Page):
page.goto("https://the-internet.herokuapp.com/upload")
page.locator("#file-upload").set_input_files("invoice.pdf")
page.get_by_role("button", name="Upload").click()
expect(page.get_by_text("File Uploaded!")).to_be_visible()Read it top to bottom: the first test tells the products call to fail, then confirms the error message shows. The second uploads a file straight to the input and checks it succeeded.
Grounded in the official Playwright (Python) docs — Frames, File Uploads, Mock APIs
All lessons in UI Automation: Selenium + Playwright + pytest
- Selenium Locators: Finding the Element You Mean
- Waits, Actions & Frames — Killing Flakiness at the Source
- Playwright: Auto-Waiting, Locators & Tracing
- pytest Deep-Dive: Fixtures, conftest, Parametrize & Markers
- Page Object Model, Done Properly
- The Hard Stuff: Dynamic Elements, iframes, Uploads & Network Stubbing