DEV Community

Cover image for Microsoft has released a Playwright-Python
Eng Soon Cheah
Eng Soon Cheah

Posted on

Microsoft has released a Playwright-Python

1. Introduction to Playwright

Playwright is a powerful Python library that can automatically perform automated operations on mainstream browsers such as Chromium, Firefox, and WebKit with only one API, and supports running in headless mode and headed mode at the same time.

The automation technology provided by Playwright is green, powerful, reliable and fast, and supports Linux, Mac and Windows operating systems.

There are friends who exaggerate: This project is a purely automated tool for the Python language, which liberates the code and realizes the automation function. Let's take a look at how to use it.

2. Use of Playwright

Install
The installation of Playwright is very simple, and it is solved in two steps.

pip install playwright
python -m playwright install
Enter fullscreen mode Exit fullscreen mode

The above two pip operations are installed separately:

  • Install Playwright dependent library, need Python3.7+
  • Install Chromium, Firefox, WebKit and other browser driver files

Record
There is no need to write a line of code to use Playwright, we only need to manually operate the browser, it will record our operations, and then automatically generate code scripts.

The following is the recorded command codegen, just one line.

python -m playwright codegen
Enter fullscreen mode Exit fullscreen mode

The usage of codegen can be viewed with --help. If it is simple to use, add the URL link directly after the command. If there are other needs, you can add options.

python -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
Enter fullscreen mode Exit fullscreen mode

Options meaning:

-o: save the recorded script to a file
--target: Specifies the language for generating scripts, there are two types of JS and Python, the default is Python
-b: Specify the browser driver

For example, I want to search on baidu.com, use the chromium driver, and save the result as a python file of my.py.

python -m playwright codegen --target python -o 'my.py' -b chromium https://www.baidu.com
Enter fullscreen mode Exit fullscreen mode

After the command line is entered, the browser will automatically open, and then you can see that every move on the browser will be automatically translated into code, as shown below.
PlayWright
After the end, the browser is automatically closed, and the generated automation script is saved to the py file.

from playwright import sync_playwright


def run(playwright):
browser = playwright.chromium.launch(headless=False)
context = browser.newContext()

# Open new page
page = context.newPage()


page.goto("https://www.baidu.com/")


page.click("input[name="wd"]")


page.fill("input[name="wd"]", "jingdong")


page.click("text="京东"")

# Click //a[normalize-space(.)='京东JD.COM官网 多快好省 只为品质生活']
with page.expect_navigation():
    with page.expect_popup() as popup_info:
        page.click("//a[normalize-space(.)='京东JD.COM官网 多快好省 只为品质生活']")
    page1 = popup_info.value
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
Enter fullscreen mode Exit fullscreen mode

In addition, playwright also provides synchronous and asynchronous API interfaces. The document is as follows.

Link: https://microsoft.github.io/playwright-python/index.html
Enter fullscreen mode Exit fullscreen mode

Synchronize
The following sample code: open three browsers in turn, go to baidu to search, take a screenshot and exit.

from playwright import sync_playwright
with sync_playwright() as p:
for browser_type in [p.chromium, p.firefox, p.webkit]:
    browser = browser_type.launch()
    page = browser.newPage()
    page.goto('https://baidu.com/')
    page.screenshot(path=f'example-{browser_type.name}.png')
    browser.close()
Enter fullscreen mode Exit fullscreen mode

asynchronous
Asynchronous operations can be combined with asyncio to perform three browser operations at the same time.

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('http://baidu.com/')
        await page.screenshot(path=f'example-{browser_type.name}.png')
        await browser.close()
        asyncio.get_event_loop().run_until_complete(main())
Enter fullscreen mode Exit fullscreen mode

Mobile
What's more, playwright can also support browser simulation on mobile terminals. The following is a piece of code provided by the official document, which simulates the Safari browser on the mobile phone iphone 11 pro at a given geographic location. First, navigate to maps.google.com, then perform the 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()
Enter fullscreen mode Exit fullscreen mode

In addition, you can also use it with the pytest plug-in. If you are interested, you can try it yourself.

3. Summary
Compared with existing automated testing tools, playwright has many advantages, including:

Support all browsers

  • Test on Chromium, Firefox and WebKit. Playwright has complete API coverage for all modern browsers, including Google Chrome and Microsoft Edge (with Chromium), Apple Safari (with WebKit) and Mozilla Firefox.
  • Cross-platform WebKit testing. Use Playwright, build with WebKit for Windows, Linux, and macOS, and test your application's behavior in Apple Safari. Test locally and on CI.
  • Test the phone. Use device emulation to test your adaptive web application in a mobile web browser.
  • There is no header and there is a header. Playwright supports headless (no browser UI) and headed (with browser UI) modes for all browsers and all platforms. The mode with header is suitable for debugging, while the header without header is suitable for CI/cloud execution.

Have fast and reliable execution

  • Automatically wait for APIs. The Playwright interaction will automatically wait until the element is ready. This can improve reliability and simplify the test writing process.
  • No timeout automation. Playwright will receive browser signals, such as network requests, page navigation and page loading events, to eliminate the annoyance of sleep interruption.
  • Keep parallel with the browser context. A single browser instance is reused for multiple parallel and isolated browser context executable environments.
  • Flexible element selector. Playwright can rely on user-oriented strings (such as text content and accessibility tags) to select elements. These strings are more flexible than selectors that are tightly coupled to the DOM structure.

Possess powerful automation functions

  • Multiple domains, pages and frames. Playwright is an out-of-process automation driver, which is not limited by the scope of JavaScript execution in the page, and can automatically execute programs with multiple pages.
  • Powerful network control. Playwright introduces context-wide network interception in order to terminate or simulate network requests.
  • Modern network functions. Playwright supports web components by inserting Yin selectors, geographic locations, permissions, Web Workers and other modern Web APIs.
  • The ability to cover all scenarios. Supports file downloading and uploading, out-of-process iframes, native input events, and even dark mode.

But it also has limitations.

  • Old version of Edge and IE11 are supported. Playwright does not support older versions of Microsoft Edge or IE11 (deprecation notice). Support for the new Microsoft Edge (on Chromium).
  • Java language binding: The Playwright API cannot currently be used in Java or Ruby. This is a temporary limitation, because Playwright aims to support bindings in any language.
  • Test on real mobile devices: Playwright uses a desktop browser to simulate mobile devices.

Although there are some limitations, now playwright has been updated to version 1.7.0. With the generation of updates, the system will be more complete. As a small white artifact, it saves so many things for everyone. We believe in its future. It will get better and better.

GitHub link: https://github.com/microsoft/playwright-python
Portal: https://playwright.dev/
Open source organization: Microsoft

Oldest comments (0)