Skip to content

Latest commit

 

History

History
76 lines (50 loc) · 2.62 KB

use-playwright-codegen-to-automate-ui-interactions.md

File metadata and controls

76 lines (50 loc) · 2.62 KB

Use Playwright Codegen to Automate UI Interactions

Playwright has a useful codegen feature that allows you to record your user interactions and generate source code automatically, saving you time and effort in your day-to-day work. If your tasks can be completed through a browser, Codegen can automate them for you.

In the following example, we'll demonstrate how to record an UI interactions that involves visiting the playwright.dev documentation, searching for the Codegen feature docs and navigating to the next page.

To get started, create a virtual environment:

python3 -m venv venv

Next, install the pytest-playwright package:

pip install pytest-playwright

Then, run the codegen command:

playwright codegen

Note that if you haven't installed any Chromium browser on your machine before, you may need to run the playwright install command.

Once you've run the codegen, two browser windows should open - one main Chromium browser and an UI for recording your UI interactions.

Here is an example of the code that is generated by the codegen after performing the actions mentioned above:

import time

from playwright.sync_api import Playwright, expect, sync_playwright


def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://playwright.dev/")

    # Tap into the search box and search "codegen"
    page.get_by_role("button", name="Search").click()
    page.get_by_placeholder("Search docs").fill("codegen")

    # Select the correct docs link
    page.locator("#docsearch-item-0").get_by_role("link",
                                                  name="Running Codegen​ Test generator").click()
    page.get_by_role(
        "heading", name="Running CodegenDirect link to Running Codegen").click()

    # The next page link is located at the bottom of the view
    page.mouse.wheel(0, 4000)

    # These sleeps commands help to slow down the UI interactions, allowing you to observe what is happening during the run.
    time.sleep(2)
    page.locator(".pagination-nav__link--next").click()

    time.sleep(3)

    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)

References: