Waits and assertions
Auto-waiting: https://playwright.dev/python/docs/actionability
Before actions playwrite check is element exactly
locater.click() wait for few time and check if
- one element
- Visible
- Stable (not animating or completed animation)
- Receives Events (not obscured by other elements)
- Enabled
give TimeoutError if not found or any check failed.
Assertions https://playwright.dev/python/docs/test-assertions
Playwright includes auto-retrying assertions that remove flakiness by waiting until the condition is met,
try:
expect(page).to_have_title(re.compile("Playwright"), timeout=2000)
except AssertionError as e:
print(f"Title mismatch: {e}")
print("Proceeding despite title mismatch...")
print(page.title()) #print page title -
Custom error message
expect(page.get_by_text("Name"), "should be logged in").to_be_visible()
WAITS:
1. locator.wait_for(): Waits until the element exists and is visible, with a default timeout of 30 seconds.
page.locator("#dynamic-div").wait_for(state="attached", timeout=5000)
#Can be "attached", "detached", "visible", or "hidden" (default is "visible").
2. wait_for_selector: Waits for an element matching a selector to appear in the DOM. It Uses a selector string directly instead of a locator object.
Use Case: When you don’t need a reusable locator.
# Wait for an element to become hidden
await page.wait_for_selector(".loading-spinner", state="hidden")
try:
page.wait_for_selector(
'input[type="email"], input[aria-label="Enter your verification code"]',
timeout=5000
)
except PlaywrightTimeoutError:
print(f"No Found {email}")
account_disabled_locator = page.locator('h1 span:has-text("Account disabled")')
password_field_locator = page.locator('input[type="password"]')
3. page.wait_for_function()
Waits for a custom JavaScript condition to evaluate to true in the browser context. Can be used with locators indirectly.
# Wait until an element's text content becomes "Success"
await page.wait_for_function(
"document.querySelector('.status').textContent === 'Success'"
)
print("Status updated to Success!")
locator = page.locator(".status")
await page.wait_for_function(
"loc => loc.textContent === 'Success'",
arg=locator
)