Playwright Python Tutorial: Part 2 – Locators and Codegen


6. Mastering Locators: The Playwright Way

In traditional web automation, you often rely on brittle selectors like lengthy XPaths or dynamically generated IDs. Playwright introduces a robust and resilient approach through Locators.

A Playwright Locator represents a way to find an element on the page at any moment. The best practice is to use user-facing locators which target elements based on how a human user perceives them.

6.1. Primary Locator Types

Locator MethodDescriptionExample (Python)
get_by_role()Locates elements based on their accessibility role (e.g., button, link, textbox). The preferred method.page.get_by_role("button", name="Submit")
get_by_text()Locates elements containing the specified text.page.get_by_text("Welcome back!")
get_by_label()Locates input elements based on the associated <label>.page.get_by_label("Username")
get_by_placeholder()Locates input elements by their placeholder attribute.page.get_by_placeholder("Enter your email")
get_by_test_id()Locates elements by a custom data-testid attribute (great for stable testing).page.get_by_test_id("product-name")
CSS SelectorClassic CSS selectors (still supported for complex cases).page.locator("#username-field")

6.2. Example: Using Locators

Let’s refactor our previous script to use the more resilient get_by_role() locator:

Python

# ... (Part 1 imports and setup)

async def run_with_locators():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        page = await browser.new_page()
        await page.goto("https://www.google.com")
        
        # 🟢 Refactored: Use get_by_role for the search input
        # The search box is a textarea with the role of 'combobox' or 'searchbox'
        search_box = page.get_by_role("combobox", name="Search")
        
        print("Typing search query using get_by_role...")
        await search_box.fill("Playwright Locators")
        
        # 🟢 Refactored: Use the Locator object to press Enter
        await search_box.press('Enter')
        
        await page.wait_for_selector('#search')
        
        title = await page.title()
        print(f"New page title: {title}")
        
        await browser.close()

if __name__ == "__main__":
    # asyncio.run(run()) # Uncomment to run the original script
    asyncio.run(run_with_locators()) # Run the new refactored script

7. Speeding Up Development with Codegen

Playwright’s Codegen is a powerful command-line tool that records your user actions in a browser and automatically generates the corresponding Python code, using the resilient Locators we just discussed.

This is excellent for bootstrapping new tests and quickly figuring out the selectors for complex forms.

7.1. How to Use Codegen

  1. Open your terminal and run the Codegen command:Bashplaywright codegen https://playwright.dev/python A new browser window will open, and a separate Playwright Inspector window will appear, ready to record.
  2. Interact with the Browser: Perform the actions you want to automate (e.g., click a link, type text, check a box).
  3. Watch the Code Generate: In the Playwright Inspector window, you will see the corresponding Python code being generated in real-time.Example generated code:Pythonawait page.get_by_role("link", name="Docs").click() await page.get_by_role("link", name="Installation", exact=True).click()
  4. Copy and Paste: Once done, click the “Copy” button in the Inspector and paste the generated code into your Python file. You can then wrap it in the standard asynchronous structure.

7.2. Codegen Tips

  • Select Browser: You can specify which browser to use (e.g., playwright codegen --browser firefox).
  • Generate File: Automatically save the generated code to a file: playwright codegen -o my_new_test.py https://example.com.
  • Learn Locators: Codegen is the best way to see how Playwright suggests locating elements on specific pages, helping you learn the best practices for Locators.

Summary and Next Steps

We’ve covered the power of Playwright’s Locators for writing reliable automation scripts and how the Codegen tool can drastically accelerate your development time. By combining these, you can build powerful and stable automation workflows quickly.

Next, we should cover how to handle common, tricky scenarios in web automation.


Leave a Reply

Your email address will not be published. Required fields are marked *