DEV Community

Karan Sharma
Karan Sharma

Posted on

Playwright with Python: Stable Locators and Better Assertions

Reliable automation starts with stable tests.

In Playwright, test stability improves when we use:

  • strong locators
  • built-in waiting behavior
  • meaningful assertions

Code example

from playwright.sync_api import sync_playwright, expect

def test_google_search_box_is_ready():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page()

        page.goto("https://www.google.com", wait_until="domcontentloaded")

        search_box = page.locator("textarea[name='q']")
        expect(search_box).to_be_visible()
        expect(search_box).to_be_editable()

        browser.close()
Enter fullscreen mode Exit fullscreen mode
## What this test checks

- Search input is visible
- Search input is editable
Enter fullscreen mode Exit fullscreen mode

Report command

py -m pytest -q test_google_playwright.py --html=playwright_report.html --self-contained-html
Enter fullscreen mode Exit fullscreen mode
## Why this approach is useful

- Fewer flaky failures
- Better confidence in test outcomes
- Cleaner reporting for review and collaboration
Enter fullscreen mode Exit fullscreen mode

Top comments (0)