Recently, Microsoft open sourced a very powerful automation project called playwright-python
It supports mainstream browsers, including: Chrome, Firefox, Safari, Microsoft Edge, etc. It also supports running in headless mode and headless mode, and provides synchronous and asynchronous APIs, which can be used in conjunction with the Pytest testing framework, and supports browsing Automatic script recording on the server side.
Project address: https://github.com/microsoft/playwright-python
For Python enthusiasts, there is an even greater benefit. This project is a pure automation tool for the Python language. It can achieve automated functions without writing a single line of code. It sounds so formidable!
You may find it a bit incredible, do you really not need to write a line of code? But it really is that powerful. Let’s take a look at this artifact together.
1. Introduction to Playwright
Playwright is a powerful Python library that uses only one API to automatically perform automated operations on mainstream browsers such as Chromium, Firefox, and WebKit, and supports running in both headless and headless modes.
The automation technology provided by Playwright is green, powerful, reliable and fast, supporting Linux, Mac and Windows operating systems.
Official website: https://playwright.dev/
According to the explanation on the official website, Playwright is officially positioned as a true end-to-end Web testing tool.
2. Playwright installation
Playwright is powerful, but its installation steps are very simple, requiring only 2 steps:
Step 1, install the playwright-python dependent library (note that the playwright library requires Python3.7+ or above)
#This may be pip/pip3, or both
pip3 install playwright
Its dependency version information can be viewed at https://pypi.org/project/playwright/.
Step 2, install mainstream browser drivers
In this way, Chromeium, Firefox, and Webkit browser drivers will be downloaded to the local
# Install the browser driver (the installation process is a little slow, please be patient)
python3 -m playwright install
If you want to check the functions supported by Playwright, you can enter directly on the command line:
python3 -m playwright help Usage: index [options] [command] Options: -V, --version output the version number -b, --browser <browserType> browser to use, one of cr, chromium, ff, firefox, wk, webkit (default: "chromium") --color-scheme <scheme> emulate preferred color scheme, "light" or "dark" --device <deviceName> emulate device, for example "iPhone 11" --geolocation <coordinates> specify geolocation coordinates, for example "37.819722,-122.478611" --lang <language> specify language / locale, for example "en-GB" --proxy-server <proxy> specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080" --timezone <time zone> time zone to emulate, for example "Europe/Rome" --timeout <timeout> timeout for Playwright actions in milliseconds (default: "10000") --user-agent <ua string> specify user agent string --viewport-size <size> specify browser viewport size in pixels, for example "1280, 720" -h, --help display help for command Commands: open [url] open page in browser specified via -b, --browser cr [url] open page in Chromium ff [url] open page in Firefox wk [url] open page in WebKit codegen [options] [url] open page and generate code for user actions screenshot [options] <url> <filename> capture a page screenshot pdf [options] <url> <filename> save page as pdf install Ensure browsers necessary for this version of Playwright are installed help [command] display help for command
As can be seen from the command line help information, Playwright supports quite a lot of functions!
3. Practical demonstration
As mentioned at the beginning, there is no need to write a line of code to use Playwright. We only need to manually operate the browser, and it will record our operations and automatically generate a code script.
1) Record script
Let’s first look at the command instructions for recording the script
python3 -m playwright codegen --help Usage: index codegen [options] [url] open page and generate code for user actions Options: -o, --output <file name> saves the generated script to a file --target <language> language to use, one of javascript, python, python-async, csharp (default: "python") -h, --help display help for command Examples: $codegen $ codegen --target=python $ -b webkit codegen https://example.com
in:
python -m playwright codegen recording script
–help help documentation
-o Directory to generate automation scripts
–target script language, including JS and Python, corresponding values are: python and javascript respectively
-b specifies the browser driver
For example, I want to search on baidu.com, use chromium driver, and save the results as a python file of mikezhou.py.
# We use the following command to open the Chrome browser and start recording the script
# Specify the generation language as: Python (default Python, optional)
# Saved file name: mikezhou.py (optional)
# Browser driver: webkit (default webkit, optional)
# Finally, follow the target website to be opened (default is just to open the browser, optional)
python3 -m playwright codegen –target python -o ‘mikezhou.py’ -b chromium https://www.baidu.com
After the command line is entered, the browser will automatically open, and then you can see that every action on the browser will be automatically translated into code, as shown below:
Finally, the automation script will be automatically generated and saved to the file mikezhou.py, and all the above manual operations will be automatically converted into code:
2) Support synchronization
The keyword for synchronization is: sync_playwright
For example, we use three browser kernels to open the browser in sequence, then search on Baidu, then take a screenshot of the search interface, and finally close the browser.
from time import sleep from playwright import sync_playwright # Note: The default is headless mode with sync_playwright() as p: # Corresponds to three browser drivers respectively for browser_type in [p.chromium, p.firefox, p.webkit]: # Specify head mode for easy viewing browser = browser_type.launch(headless=False) page = browser.newPage() page.goto('http://baidu.com')
from playwright import sync_playwright def run(playwright): browser = playwright.chromium.launch(headless=False) context = browser.newContext() # Open new page page = context.newPage() # Go to https://www.baidu.com/ page.goto("https://www.baidu.com/") # Click input[name="wd"] page.click("input[name="wd"]") # Fill input[name="wd"] page.fill("input[name="wd"]", "禾大") #PressCapsLock page.press("input[name="wd"]", "CapsLock") # Fill input[name="wd"] page.fill("input[name="wd"]", "Practical Guide to Automated Testing ") # Press Enter page.press("input[name="wd"]", "Enter") # assert page.url() == "https://www.baidu.com/s?ie=utf-8 & amp;f=8 & amp;rsv_bp=1 & amp;rsv_idx=1 & amp;tn =baidu & amp;wd=Practical Guide to Automated Testing& amp;fenlei=256 & amp;rsv_pq=af40e9aa00012d5a & amp;rsv_t=c659gpz2/jri1SAoIXdT9gP+mrqufXzRtMSSAL0n0fv7GSoLF5vaiNVPA3U & amp;rqlang=cn & amp;rs v_enter=1 & amp;rsv_dl= tb & amp;rsv_sug3=38 & amp;rsv_sug1=22 & amp;rsv_sug7=100 & amp;rsv_sug2=0 & amp;rsv_btype=i & amp;inputT=8034 & amp;rsv_sug4=9153" # Close page page.close() #--------------------- context.close() browser.close() with sync_playwright() as playwright: run(playwright) #Perform a search operation page.fill("input[name="wd"]", "Practical Guide to Automated Testing") with page.expect_navigation(): page.press("input[name="wd"]", "Enter") # Wait for the page to load completely page.waitForSelector("text=Search tool") # screenshot page.screenshot(path=f'test-{browser_type.name}.png') # Sleep 3s sleep(3) # Close browser browser.close()
It should be pointed out that the built-in API of playwright-python basically covers common automation operations.
3) Support asynchronous
The keyword of asynchronous synchronization is: async_playwright. Asynchronous operations can be combined with asyncio to perform three browser operations at the same time.
import asyncio from playwright import async_playwright # Asynchronous execution async def main(): async with async_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: # Specify head mode for easy viewing browser = await browser_type.launch(headless=False) page = await browser.newPage() await page.goto('http://baidu.com') #Perform a search operation await page.fill("input[name="wd"]", "A practical guide to automated testing") await page.press("input[name="wd"]", "Enter") # Wait for the page to load completely await page.waitForSelector("text=search tool") # screenshot await page.screenshot(path=f'test-{browser_type.name}.png') await browser.close() asyncio.get_event_loop().run_until_complete(main())
4) Support mobile terminal
What’s even more amazing is that playwright can also support browser emulation on the mobile side. The following is a piece of code provided by the official document, which simulates the Safari browser on the iPhone 11 pro at a given geographical location. First, navigate to maps.google.com, then perform positioning and take a screenshot.
from playwright import sync_playwright with sync_playwright() as p: iphone_11 = p.devices['iPhone 11 Pro'] browser = p.webkit.launch(headless=False) context = browser.newContext( **iphone_11, locale='en-US', geolocation={ 'longitude': 12.492507, 'latitude': 41.889938 }, permissions=['geolocation'] ) page = context.newPage() page.goto('https://maps.google.com') page.click('text="Your location"') page.screenshot(path='colosseum-iphone.png') browser.close()
5) Support Pytest framework
In addition, it can also be used with the pytest plug-in to give an official website example:
def test_playwright_is_visible_on_google(page): page.goto("https://www.google.com") page.type("input[name=q]", "Playwright GitHub") page.click("input[type=submit]") page.waitForSelector("text=microsoft/Playwright")
Of course, in addition to the features listed above, there are more interesting uses, and interested readers can explore them on their own.
4. Summary
Playwright has many advantages over existing automated testing frameworks, such as:
Cross-browser, supports Chromium, Firefox, and WebKit;
Cross-operating system, supporting Linux, Mac, and Windows;
It can provide the function of recording and generating code to free your hands;
Available on mobile;
The current shortcoming is that the ecosystem and documentation are not very complete. For example, there is no API Chinese documentation, and there are no good tutorials and examples for learning. But I believe that as more and more people know about it, the future will get better and better.
Finally, let me tell you a little secret. Playwright is a cross-language automation framework. In addition to supporting Python, it also supports Java, JS, etc. More detailed functions can be unlocked through official projects~
Finally, I would like to thank everyone who read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, if you can use it, you can just take it away:
This information should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can also help you!