SoFunction
Updated on 2024-11-16

Implementation of Web Automation Testing in Playwright

1. Mainstream framework awareness

Summary:

  • Since Selenium hasn't changed much between and two iterations, Selenium's reign may be less secure with the new framework.
  • The follow-up Cypress, TestCafe, Puppeteer is known as the post-Selenium era of Web UI automation troika. But because these three frameworks are based on JavaScript development, and none of them support Python, so the usage rate is not very high.
  • playwright, on the other hand, combines the strengths of the above frameworks and provides a great experience that may become popular in the future.

2. Playwright Awareness

About Playwright

  • In 2020, Microsoft open-sourced a tool called Playwright, which is as easy to start as Selenium, supports multiple languages (Python, Java, .NET), multiple browsers (Chromium, Firefox, Webkit), and cross-platform (Windwos, Linux, Mac OS)
  • Playwright supports both interface automation and UI automation, providing reliable end-to-end testing capabilities for modern web applications.

The Playwright Advantage

  • 1) Automatic wait function makes automation more reliable
  • (2) Automatic tracing: you can easily configure the retry policy, automatic tracing results to record in the form of screenshots and screen recordings.
  • (3) Assertion mechanism: it will be automatically asserted according to the network environment until a certain condition is met.
  • 4) Asynchronous execution: Playwright is based on socket for two-way communication, supports synchronous and asynchronous execution of two ways
  • (5) can run multi-page simulation scenarios: Playwright is to manage the browser through the context, equivalent to each test case will create an independent context, the browser's context is in fact a completely new browser, the benefits of this approach is to speed up at the same time but also to achieve the isolation of the test and the test, so that the test results are more accurate, so it can be realized in parallel execution.
  • 6) Powerful toolset: we also provide a powerful toolset, such as: script recording tool codegen, scripting and debugging tools playwright and so on.

3. Playwright environment setup

Python environment: python interpreter + IDE tools, for those who don't know how to install them:python3.4 + pycharm environment installation + pycharm use

Playwright Environment:

Install Playwright:pip install playwright -i /simple

Install the built-in browser (chromium, firefox, webkit): playwright install

4. Getting Started with Playwright

1) Script Recording

Case 1: realize web ui automation, open the browser, visit the test pie, click on the login after the login operation (enter the user name, password, click on the login button)

Operational Steps:

  • Step 1: Enter the command in pycharm -- Terminal:playwright codegenThe browser and the Playwright Inspector tool will automatically open, and the Playwright Inspector tool will automatically enable recording.
  • Step 2: Perform relevant actions in the open browser, such as accessing the address, clicking or typing actions
  • Step 3: Once the operation is complete, in the Playwright Inspector click on theRecordStop recording and just copy the code
from playwright.sync_api import Playwright, sync_playwright, expect

def run(playwright: Playwright) -> None:
    browser = (headless=False)
    context = browser.new_context()
    page = context.new_page()
    ("http://175.178.53.95:8081/")
    page.get_by_text("Login").click()
    page.get_by_placeholder("Username/email/mobile phone number").click()
    page.get_by_placeholder("Username/email/mobile phone number").fill("kemi")
    page.get_by_placeholder("Username/email/mobile phone number").press("Tab")
    page.get_by_placeholder("Password.").fill("123456")
    ()  # Breakpoint debugging capabilities
    page.get_by_role("button", name="Login").click()

    # ---------------------
    ()
    ()


with sync_playwright() as playwright:
    run(playwright)

2) Recording tools to quickly locate elements

If I write my own code and need to locate an element, I can quickly get information about the element's location by using the Playwright Inspector tool's Pick locator, as shown in the following screenshot:

Playwright supports two broad categories of element positioning methods, including:

1) get_by method

  • get_by_id: Find an element by its id attribute, e.g. element = page.get_by_id("my-id")
  • get_by_name: Find an element by its name attribute, e.g.: element = page.get_by_name("my-name")
  • get_by_text: Find an element by its text content, e.g. element = page.get_by_text("Submit")
  • get_by_title: Find an element by its title attribute, e.g.: element = page.get_by_title("my-title")
  • get_by_placeholder: Find elements by their placeholder attribute, e.g. element = page.get_by_placeholder("my-placeholder")
  • get_by_selector: Find elements by CSS selector, e.g. element = page.get_by_selector("#submit-button")
  • get_by_xpath: Find elements by XPath expressions, e.g. element = page.get_by_xpath("//div[@class='my-class']")
  • get_by_label: Finds an element based on the value of the label attribute, similar to the label tag and the corresponding for attribute in HTML.
  • get_by_role: locate elements by role, e.g. element = page.get_by_role("button", name="Submit")

2) Approach

  • Positioning elements by ID: use the("#element-id")maybe('id=element-id')Positioning.
  • Positioning elements via CSS selectors: use the("css=selector")Positioning. For example: element = ("button#submit-button")
  • Positioning elements via XPath expressions: use the("xpath=expression")Positioning. For example: element = ("//button[@id='submit-button']")
  • Positioning elements by name: use the("name=element-name")Positioning.
  • Positioning elements by link text: use the("text=link-text")Positioning.
  • Positioning elements via partially linked text: use("partial_text=partial-link-text")Positioning.
  • Locating an element by its attributes: use the("[attribute=value]")Positioning.
  • Positioning elements by tag name: Use the("tag=tag-name")Positioning.

4. Pytest+Allure+Playwright Full Project Demo

1) Scripts to test cases

Case Requirement: Convert the login operation of the above test pie into a test case

Operational Steps:

  • Step 1: Enter the command in pycharm -- Terminal:playwright codegenThe browser and the Playwright Inspector tool will automatically open, and the Playwright Inspector tool will automatically enable recording.
  • Step 2: Perform relevant actions in the open browser, such as accessing the address, clicking or typing actions
  • Step 3: Once the operation is complete, in the Playwright Inspector click on theRecordStop recording
  • Step 4: Select pytest under Python in Target, it will automate the recorded code into test cases, and then copy the code. The specific operation is shown in the following screenshot:

The code is as follows:

from playwright.sync_api import Page, expect

def test_example(page: Page) -> None:
    ("http://175.178.53.95:8081/")
    page.get_by_text("Login").click()
    page.get_by_placeholder("Username/email/mobile phone number").click()
    page.get_by_placeholder("Username/email/mobile phone number").fill("kemi")
    page.get_by_placeholder("Username/email/mobile phone number").press("Tab")
    page.get_by_placeholder("Password.").fill("123456")
    page.get_by_role("button", name="Login").click()

You must install the plug-in before executing the use case, otherwise it will report an error, because the use case has only core business operations, there is no browser, context, page initialization, after installing the plug-in will automatically do these initialization operations, so that the execution of the use case will not report an error. Command:pip install pytest-playwright

2) Data-driven

Set pytest's parametrize implementation of data-driven

import pytest
from playwright.sync_api import Page, expect

# Test case data
case_data = [{'caseid':1,'username':'kemi123', 'password':'kemi123'},
             {'caseid':2,'username':'zhangsan', 'password':'123456'},
             {'caseid':3,'username':'lisi', 'password':'123456'}]

# Data-driven
@('case', case_data)
def test_example(page: Page,case) -> None:
    username = case['username']
    password = case['password']

    ("http://175.178.53.95:8081/")
    page.get_by_text("Login").click()
    page.get_by_placeholder("Username/email/mobile phone number").click()
    page.get_by_placeholder("Username/email/mobile phone number").fill(username)
    page.get_by_placeholder("Username/email/mobile phone number").press("Tab")
    page.get_by_placeholder("Password.").fill(password)
    page.get_by_role("button", name="Login").click()
    (path=f"images/login/log in{case['caseid']}.png")  # Save screenshot to specified location

3) The report shows

After executing the use case via pytest, generate a report via the command: allure serve outputs/allure and view the report display, screenshot below:

To this article on Playwright Web automation testing in the implementation of the article is introduced to this, more related Playwright Web automation testing content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!