Microsoft automated test tool Playwright Quick Start Guide

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

1. Why Playwright

1.1 advantages of playwright

(1) Selenium The browser needs to be operated through WebDriver; Playwright interacts with the browser through developer tools. The installation is simple and does not need to install various drivers.

(2) Playwright supports almost all languages and does not rely 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), which can automatically obtain the actual situation of the browser.

(4) Playwright is auto wait.

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

Known limitations

(1) Playwright does not support older versions of Microsoft Edge or IE11. Support the new Microsoft Edge (on Chromium); Therefore, items with mandatory requirements for browser version are not applicable.

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

(3) The mobile terminal test simulates the mobile device through the desktop browser (equivalent to the built-in simulator), which cannot control the real machine.

2. Playwright use

2.1 installation

(1) Install the Playwright dependency Library (Playwright supports async \ wait syntax, so Python 3.7 + is required)

pip install playwright

(2) Install Chromium, Firefox WebKit Driver file of browser (built-in browser)

python -m playwright install

2.2 automatic recording

(1) On the command line, type -- help to see all the options that can be followed

python -m playwright codegen --help

(2) The starting page is xingzhiai Cn start recording

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

(3) Open Xingzhen Cn, driven by Chromium, save the result as my python file of PY

python -m playwright codegen --target python -o 'my.py' -b chromium https://xingzheai.cn/

  • -target: Specifies the language for generating scripts, including JS and Python. The default is Python
  • -b: Specify browser driver
  • -o: Save the recorded script to a file

2.3 customized preparation

(1) Element positioning

  • Select a single element: querySelector(engine=body)
  • Select multiple elements: querySelectorAll(engine=body)
  • Select a single element and automatically wait: waitForSelector(engine=body)

There are 8 positioning modes of By, actually 4

  • id, name, tag name, class name (java and python classify these four as CSS)
  • xpath,link text,partial link text,css selector

W3C standard webDriver The protocol has five positioning modes

  • CSS,Link text,Partial link text,Tag name,XPath

Playwright summarizes selectors into three types

  • CSS, XPATH (supporting logical expressions and functions), TEXT

(2) Selector rule

  • CSS: ID selector, class selector, element selector, attribute selector, wildcard selector and hierarchy selector.
  • XPath: XML path language. It can navigate XML documents through "path identifier". It can also be used in XML like (HTML).
  • Text: structured content (html, xml, json) uses fuzzy matching (ignoring case, ignoring space before and after, searching substring) and exact matching, while unstructured content uses regular matching.

(3) Element common operations

  • Drop down selection boxes: selectoption, 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 recording: screenshot and recordVideo

2.4 network interception (Mock interface), for example:

page = context.newPage()
def Whether_intercept() -> bool:
    return True  


def handler(route:Route):
    print(route.request.url)
    
    
    
    
    
    route.fulfill(
        status=302,
        headers={
            'Location' : "https://xingzheai.cn/"
        }
    )
page.route(Whether_intercept,handler)

2.5 synchronous execution, for example:

from playwright import sync_playwright with sync_playwright() as p:
    for browser_type in [p.chromium, p.firefox, p.webkit]:
         
        browser = browser_type.launch(headless=False)
        page = browser.newPage()
        page.goto('https://xingzheai.cn/')
        
        page.waitForSelector("text=Intelligent content audit")
        page.screenshot(path=f'example-{browser_type.name}.png')
        browser.close()

2.6 asynchronous execution, for example:

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=Intelligent content audit")
       	 	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, examples are 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="Intelligent content audit"')         
    assert "Intelligent content audit" == element.textContent()

2.8 mobile terminal operation, examples are as follows:

At present, there are few analog models supported. Refer to: Simulation equipment 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="Intelligent content audit"')
    
    
    sleep(10)
    browser.close()

3. Summary

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

Reprint https://blog.csdn.net/suiyuejian/article/details/113541451

Keywords: Python crawler microsoft

Added by ErikTheViking on Wed, 23 Feb 2022 07:56:06 +0200