Quick Start Guide for Automation Artifact Playwright

Playwright is a new generation of automated testing tools released by Microsoft in early 2020. Compared with Selenium, which is currently the most commonly used, it can automatically perform automated operations on mainstream browsers such as Chromium, Firefox, and WebKit using only one API. As a pure automation tool for the Python language, automation can be realized faster in regression testing.

1. Why choose Playwright

1.1 Advantages of Playwright

(1) Selenium needs to operate the browser through WebDriver; Playwright interacts with the browser through developer tools, and the installation is simple and does not require the installation of various drivers.

(2) Playwright supports almost all languages ​​and does not depend on various drivers. It starts faster by calling the built-in browser.

(3) Selenium is based on HTTP protocol (one-way communication), and Playwright is based on Websocket (two-way communication) to automatically obtain the actual situation of the browser.

(4) Playwright waits automatically.

  • Wait for the element to appear (when positioning the element, wait for 30s automatically, the waiting time can be customized, in milliseconds)
  • Wait for an event to occur

1.2 Known limitations

(1) Playwright does not support older versions of Microsoft Edge or IE11. Supports the new Microsoft Edge (on Chromium); so projects with strict browser version requirements are not applicable.

(2) Websites that require SSL certificates for access may not be recorded, and the process needs to be positioned and written separately.

(3) The mobile terminal test simulates the mobile device through a desktop browser (equivalent to its own simulator) and cannot control the real device.

2. Playwright use

2.1 Installation

(1) Install Playwright dependent libraries (Playwright supports Async\Await syntax, so Python3.7+ is required)

pip install playwright

(2) Install driver files for Chromium, Firefox, WebKit and other browsers (built-in browser)

python -m playwright install

2.2 Automatic recording

(1) Type --help on the command line to see all options that can be followed

python -m playwright codegen --help

(2) Start recording from the start page http://xingzheai.cn

python -m playwright codegen https://xingzheai.cn/

(3) Open http://xingzheai.cn , use Chromium driver, and save the result as a python file my.py

python -m playwright codegen --target python -o 'my.py' -b chromium https://xingzheai.cn/
  • -target: specifies the language for generating scripts, there are two types: JS and Python, the default is Python
  • -b: Specify browser driver
  • -o: Save the recorded script to a file

2.3 Customized writing

(1) Element positioning

  • Select a single element: querySelector(engine=body)
  • Select multiple elements: querySelectorAll(engine=body)
  • Select a single element and wait automatically: waitForSelector(engine=body)
By’s 8 positioning methods, the actual number is 4
  • id, name, tag name, class name (java and pythona classify these 4 types as CSS)
  • xpath、link text、partial link text、css selector
The webDriver protocol specified by the W3C standard has 5 positioning methods
  • CSS、Link text、Partial link text、Tag name、XPath
Playwright summarizes selectors into 3 types
  • CSS, XPATH (supports logical expressions and functions), TEXT

(2) Selector rules

  • CSS: ID selector, class selector, element selector, attribute selector, wildcard selector, hierarchical selector.
  • XPath: XML path language, which navigates XML documents through "path identifiers" and can also be used in XML-like languages ​​(HTML).
  • Text: Structured content (html, xml, json) uses fuzzy matching (ignoring case, ignoring leading and trailing spaces, searching for substrings) and exact matching, and unstructured content uses regular matching.

(3) Common operations on elements

  • Drop-down selection box: selectOpion, value, labei, index
  • File upload: setInputFiles, single file, multiple files, drag-and-drop upload
  • Mouse click: click, dbclick
  • Mouse drag: down, up
  • Mouse movement: move
  • Touch screen: tag
  • Keyboard key: press
  • Screen capture and screen recording: screenshot, recordVideo

2.4 Network interception (Mock interface), examples are as follows:

page = context.newPage()
def Whether_intercept() -> bool:
    return True  #进行拦截
# return False #不进行拦截

def handler(route:Route):
    print(route.request.url)
    #正常访问
    # route.continue_()
    #拒绝访问
    # route.abort("网络拦截")
    # 重定向到非目标地址
    route.fulfill(
        status=302,
        headers={
            'Location' : "https://xingzheai.cn/"
        }
    )
page.route(Whether_intercept,handler)

2.5 Synchronous execution, the example is as follows:

#依次打开三个浏览器,前往行者官网,截图后退出。
from playwright import sync_playwright with sync_playwright() as p:
    for browser_type in [p.chromium, p.firefox, p.webkit]:
         # 指定为有头模式,Ture为无头模式
        browser = browser_type.launch(headless=False)
        page = browser.newPage()
        page.goto('https://xingzheai.cn/')
        # 等待页面加载完全后截图
        page.waitForSelector("text=智能内容审核")
        page.screenshot(path=f'example-{browser_type.name}.png')
        browser.close()

2.6 Asynchronous execution, examples are as follows:

#同时进行三个浏览器操作
import asyncio
from playwright import async_playwright
async def main():
async with async_playwright() as p:
     for browser_type in [p.chromium, p.firefox, p.webkit]:
         browser = await browser_type.launch()
         page = await browser.newPage()
         await page.goto('https://xingzheai.cn/')
         await page.waitForSelector("text=智能内容审核")
         await page.screenshot(path=f'example-{browser_type.name}.png')
         await browser.close()
         asyncio.get_event_loop().run_until_complete(main())

2.7 Pytest combination, the example is as follows:

Installation: pip install pytest-playwright

def test_playwright(page):
    page.goto("https://xingzheai.cn/")
    with page.expect_popup() as popup_info:         
    page.click('text="智能内容审核"')         
    assert "智能内容审核" == element.textContent()

2.8 Mobile terminal operation, examples are as follows:

Currently there are few simulation models supported, please refer to: Simulation device list

from time import sleep
from playwright import sync_playwright  
with sync_playwright() as p:
    GalaxyS5 = p.devices['Galaxy S5']
    browser = p.chromium.launch(headless=False)
    context = browser.newContext(**GalaxyS5)
    page = context.newPage()
    page.goto('https://xingzheai.cn/')
    page.click('text="智能内容审核"')
    # 截图
    # page.screenshot(path='colosseum-GalaxyS5.png')
    sleep(10)
    browser.close()

3. Summary

As a new generation of automated testing tools, Playwright has been comprehensively improved in terms of ease of use and practicality compared to Selenium. It is simple but not simple. I believe that using this tool can help us improve the efficiency of automation.

Guess you like

Origin blog.csdn.net/z1521695011/article/details/131393014