playwright for Web automated testing: an overview

Playwright is a Web UI automated testing tool developed by Microsoft. It supports Node.js, Python, C# and Java languages...
Script recording
Open web page
screenshot

Playwright is a Web UI automated testing tool developed by Microsoft. It supports Node.js, Python, C# and Java languages. This article will introduce the features of playwright and its simple use.

catalogue

playwright property

playwright has the following characteristics:

1, Support all mainstream browsers

  • Supports all mainstream browsers: Google Chrome and Microsoft Edge browser based on Chromium kernel), Apple Safari and Mozilla Firefox browser based on WebKit kernel, and does not support IE11.
  • Cross platform: Windows, Linux and macOS
  • It can be used to simulate the testing of mobile WEB applications, and does not support testing on real machines.
  • Headless mode (default) and headless mode are supported

2, Fast and reliable execution

  • Auto wait element
  • Playwright is based on the Websocket protocol and can accept the signals from the browser (server). selenium uses the HTTP protocol and can only initiate requests from the client.
  • Browser context parallelism: create multiple browser contexts under a single browser instance, and each browser context can process multiple pages.
  • Flexible element selection: elements can be selected using text and accessible tags.

3, Strong automation capability

  • playwright is an out of process automation driver. It is not limited by the execution range of JavaScript in the page and can automatically control multiple pages.
  • Powerful network control: Playwright introduces context wide network interception to stub and simulate network requests.
  • Modern web features: support Shadow DOM selection, element location, page prompt processing, Web Worker and other web APIs.
  • Cover all scenarios: support file download, upload, OOPIF (out of process iframes), input, click, dark mode, etc.
install

Playwright is easy to install without downloading the browser driver separately. pip installation:

pip install playwright playwright install # Install supported browsers: cr, chromium, ff, firefox, wk and webkit playwright install chromium # Installs the specified chromium browser

Browser dependencies will be automatically downloaded during installation. windows system is in the path of% userprofile% \ appdata \ local \ MS playwright.

Command line tools

Script recording

In the command line window, use the following syntax format for script recording:

npx playwright codegen [options] [url]

options parameter:

  • -o. -- output < file name >: save the generated script
  • --Target < language >: the generated script language. You can set JavaScript, test, python, python async and csharp. The default is python.
  • -b. -- browser < BrowserType >: you can select cr, chromium, ff, firefox, wk and webkit as the browser to use. The default is chromium.
  • --Channel < channel >: chromium version, such as chrome, chrome beta, msedge dev, etc,
  • --Color scheme < scheme >: the color theme of the simulator. You can choose light or dark style.
  • --Device < devicename >: an emulated device, such as iPhone 11.
  • --Save storage < filename >: saves the context state. It is used to save cookies and localStorage. It can be used for reuse. For example, playwright CodeGen -- save storage = auth.json
  • --Load storage < filename >: load -- save storage saved data and reuse authentication data.
  • --Proxy server < proxy >: Specifies the proxy server
  • --Timezone < time zone >: Specifies the time zone
  • --Geography < coordinates >: specify geographic coordinates
  • --lang <language>: specify language / area, such as Chinese mainland: zh-CN
  • --Timeout < timeout >: timeout, positioning milliseconds, default 10000ms
  • --User agent < UA string >: user agent
  • --Viewport size < size >: browser window size
  • -h. -- help: view help information

Example: simulate the iPhone 12 Pro device, open Baidu, use the Chromium driver, set the generated script language to python, and save the name as test_playwright.py:

playwright codegen -o test_playwright.py --target python -b chromium --device="iPhone 12 Pro" https://www.baidu.com/

The operation on the page will generate the corresponding script code.

Open web page

Syntax format:

npx playwright open [options] [url]

playwright open supports other parameters of playwright codegen except that there are no - o and -- target options parameters.

playwright open https://www.baidu.com / # by default, it is opened with Chromium playwright wk https://www.baidu.com / # use WebKit to open playwright open --device="iPhone 12 Pro" https://www.baidu.com / # use iPhone 12 Pro simulator to open

screenshot

Syntax format:

npx playwright screenshot [options] <url> <filename>

The options parameter is similar to the options of playwright codegen, which can be viewed using the playwright screenshot --help command.

playwright screenshot --device="iPhone 12 Pro" -b wk https://www.baidu.com/ baidu-iphone.png # capture the displayed page playwright screenshot --full-page --device="iPhone 12 Pro" -b wk https://www.baidu.com/ baidu-iphone-full-page.png # intercept all current pages
Synchronous and asynchronous API s

Playwright supports both synchronous and asynchronous APIs. To use asynchronous APIs, you need to import the asyncio library, which is a library that can be used to implement Python collaboration. For more details, please refer to Python co process .

The following describes how to write a simple playwright automation script in python.

There are two test cases in total. The steps of case 1 are as follows:

  1. chrome browser opens Baidu
  2. Enter "test" in the search box
  3. Click Baidu to search
  4. Click on page 2 of the search results

Use case 2 steps:

  1. Open Sogou search in chrome browser
  2. Enter "test" in the search box
  3. Click Sogou search
  4. Click on page 2 of the search results

1. Synchronization mode

import time from playwright.sync_api import sync_playwright def testcase1(): print('testcase1 start') with sync_playwright() as p: browser = p.chromium.launch(headless=False) page = browser.new_page() page.goto("https://www.baidu.com/") print(page.title()) page.fill("input[name=\"wd\"]", "test") page.click("text=use Baidu Search") page.click("#page >> text=2") browser.close() print('testcase1 done') def testcase2(): print('testcase2 start') with sync_playwright() as p: browser2 = p.chromium.launch(headless=False) page2 = browser2.new_page() page2.goto("https://www.sogou.com/") print(page2.title()) page2.fill("input[name=\"query\"]", "test") page2.click("text=Sogou search") page2.click("#sogou_page_2") browser2.close() print('testcase2 done') start = time.time() testcase1() testcase2() end = time.time() print('Running time: %s Seconds'%(end-start))

Execution results:

testcase1 start Baidu once, you know testcase1 done testcase2 start Sogou search engine - Internet starts with Sogou testcase2 done Running time: 11.476110458374023 Seconds

2. Asynchronous mode

import asyncio import time from playwright.async_api import async_playwright async def testcase1(): print('testcase1 start') async with async_playwright() as p: browser = await p.chromium.launch(headless=False) page = await browser.new_page() await page.goto("https://www.baidu.com/") print(await page.title()) await page.fill("input[name=\"wd\"]", "test") await page.click("text=use Baidu Search") await page.click("#page >> text=2") await browser.close() print('testcase1 done') async def testcase2(): print('testcase2 start') async with async_playwright() as p: browser2 = await p.chromium.launch(headless=False) page2 = await browser2.new_page() await page2.goto("https://www.sogou.com/") print(await page2.title()) await page2.fill("input[name=\"query\"]", "test") await page2.click("text=Sogou search") await page2.click("#sogou_page_2") await browser2.close() print('testcase2 done') async def main(): task1 = asyncio.create_task(testcase1()) task2 = asyncio.create_task(testcase2()) tasks = [task1,task2] print('before await') await asyncio.gather(*tasks) start = time.time() asyncio.run(main()) end = time.time() print('Running time: %s Seconds'%(end-start))

Execution results:

before await testcase1 start testcase2 start Baidu once, you know Sogou search engine - Internet starts with Sogou testcase1 done testcase2 done Running time: 6.0248863697052 Seconds

It can be seen that the use of asynchronous programming can significantly improve the test efficiency.

browser

As mentioned earlier, Playwright supports all mainstream browsers. The following describes the startup methods of four browsers:

# chrome browser = p.chromium.launch(channel="chrome", headless=False) # Microsoft Edge browser = p.chromium.launch(channel="msedge", headless=False) # firefox browser = p.firefox.launch(headless=False) # webkit browser = p.webkit.launch(headless=False)
Browser context

Before web automation control, the browser needs to be instantiated, such as:

browser = p.chromium.launch(channel="chrome", headless=False)

Browser is a Chromium instance. Creating an instance is actually resource consuming. Playwright supports the creation of multiple browser contexts under one browser instance. The creation of BrowserContext is fast and consumes less resources than creating a browser instance. For multi page scenarios, you can use the method of creating browser context.

import asyncio from playwright.async_api import async_playwright async def testcase1(): print('testcase1 start') async with async_playwright() as p: browser = await p.chromium.launch(headless=False) page = await browser.new_page() await page.goto("https://www.baidu.com/") print(await page.title()) await page.fill("input[name=\"wd\"]", "test") await page.click("text=use Baidu Search") await page.click("#page >> text=2") context = await browser.new_context() page2 = await context.new_page() await page2.goto("https://www.sogou.com/") print(await page2.title()) await page2.fill("input[name=\"query\"]", "test") await page2.click("text=Sogou search") await page2.click("#sogou_page_2") print(await page.title()) print('testcase1 done') asyncio.run(testcase1())
Multi page

A browser context can have multiple pages, that is, multiple windows.

async def testcase2(): print('testcase2 start') async with async_playwright() as p: browser = await p.chromium.launch(headless=False) context = await browser.new_context() page1 = await context.new_page() await page1.goto("https://www.sogou.com/") print(await page1.title()) await page1.fill("input[name=\"query\"]", "test") await page1.click("text=Sogou search") await page1.click("#sogou_page_2") page2 = await context.new_page() await page2.goto("https://www.baidu.com/") print(await page2.title()) print('testcase2 done')
Assert

assert can be used in Python:

assert page.title() == "Baidu once, you know"

In addition to using assert assertions, you can also use the more powerful assertion method Hamcrest, which has a wealth of assertion matchers.

Hamcrest documentation: https://pyhamcrest.readthedocs.io/en/v2.0.2/tutorial/

Install PyHamcrest:

pip install PyHamcrest
from hamcrest import * assert_that(page.title(), equal_to("Baidu once, you know"))
--THE END--

2 November 2021, 10:12 | Views: 9614

Add new comment

For adding a comment, please log in
or create account

0 comments