Home > Backend Development > Python Tutorial > Microsoft's Python novice tool is so delicious!

Microsoft's Python novice tool is so delicious!

WBOY
Release: 2023-04-12 10:55:05
forward
1415 people have browsed it

Microsoft's Python novice tool is so delicious!

Hello everyone, I am a rookie!

I recently visited the G website and found that Microsoft has open sourced a project called "playwright-python" as a rising project.

Microsoft's Python novice tool is so delicious!

Playwright is a pure automation tool for the Python language. It can automatically execute Chromium, Firefox and WebKit browsers through a single API. It can achieve automation without writing code. Function.

Although the testing tool selenium has complete documentation, its learning cost prohibits many novices. In contrast, playwright-python is simply an artifact for novices.

Does Playwright really work with Python? The answer is yes, Microsoft is ready with Playwright for Python. Breaking API changes may occur. But the odds are that that won't happen, and Microsoft says it will only do so if they know it will improve your experience with the new library.

However, Microsoft also reminds that some edge cases of vendor-specific APIs are not yet supported, such as collecting Chromium tracking, coverage reports, etc.

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 using only one API, and also supports headless browsers. mode, headless mode operation.

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

Some friends also praised this: As a pure automation tool for the Python language, this project liberates the code and realizes the automation function. Let’s see how to use it.

2. Use Playwright to install

The installation of Playwright is very simple and can be solved in two steps.

安装playwright库
pip install playwright
安装浏览器驱动文件(安装过程稍微有点慢)
python -m playwright install
Copy after login

The above two pip operations are installed separately:

  • Installing Playwright dependent libraries requires Python3.7
  • Install drivers for Chromium, Firefox, WebKit and other browsers File

Recording

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 then automatically generate a code script.

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

命令行键入 --help 可看到所有选项
python -m playwright codegen
Copy after login

The usage of codegen can be viewed using --help. If it is simple to use, just add the url link directly after the command. If you have 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, --helpdisplay help for command
Examples:
 $ codegen
 $ codegen --target=python
 $ -b webkit codegen https://example.com
Copy after login

options meaning:

  • -o: Save the recorded script to a file
  • --target: Specify the language to generate the script, including JS and Python Two types, 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 my.py python file.

python -m playwright codegen --target python -o 'my.py' -b chromium https://www.baidu.com
Copy after login

After entering the command line, 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.

Microsoft's Python novice tool is so delicious!

# Automatically close the browser after completion and save the generated automation script to a 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
Copy after login

In addition, playwright also provides synchronous and asynchronous API interfaces, the documents are as follows.

  • Link: https://microsoft.github.io/playwright-python/index.html

Sync

The following sample code: Open in sequence For three browsers, 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()
Copy after login

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())
Copy after login

Mobile terminal

What’s even more amazing is that playwright can also support mobile browser simulation. 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()
Copy after login

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

3. Summary

Playwright has many advantages over existing automated testing tools, including:

Support for all browsers

  • Tested 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. Test how your app behaves in Apple Safari using Playwright, built with WebKit for Windows, Linux, and macOS. Tested locally and on CI.
  • Test the phone. Test your responsive web applications in mobile web browsers using device emulation.
  • Without header and with header. Playwright supports headless (no browser UI) and headless (with browser UI) modes for all browsers and all platforms. Header mode is suitable for debugging, while headerless mode is suitable for CI/cloud execution.

Have fast and reliable execution

  • Auto-wait APIs. Playwright interactions automatically wait until the element is ready. This improves reliability and simplifies the test writing process.
  • No timeout automation. Playwright receives browser signals such as network requests, page navigation, and page load events to eliminate sleep-interrupted annoyances.
  • Stay parallel to the browser context. Reuse a single browser instance for multiple parallel isolated browser context executable environments.
  • Sexual element selector. Playwright can select elements relying on user-facing strings such as text content and accessibility tags. These strings are more flexible than selectors that are tightly coupled to the DOM structure.

Has powerful automation capabilities

  • Multiple domains, pages and frames. Playwright is an out-of-process automation driver that is not limited by the scope of JavaScript execution within a page and can automate scenarios with multiple pages.
  • Powerful network control. Playwright introduces context-wide network interception to terminate or simulate network requests.
  • Modern network features. Playwright supports web components with inserted selectors, geolocation, permissions, web workers and other modern web APIs.
  • The ability to cover all scenarios. Supports file downloads and uploads, out-of-process iframes, native input events, and even dark mode.

But it also has limitations

  • Old Edge and IE11 support. Playwright does not support older versions of Microsoft Edge or IE11 (deprecation notice). Support for new Microsoft Edge (on Chromium).
  • Java Language Bindings: The Playwright API is not currently available in Java or Ruby. This is a temporary limitation, as Playwright is designed to support bindings for any language.
  • Test on real mobile devices: Playwright uses a desktop browser to emulate a mobile device.

Although there are some limitations, playwright has now been updated to version 1.7.0. With each generation of updates, the system will be more perfect. As a novice artifact, it saves everyone So many things, we believe its future will get better and better.

The above is the detailed content of Microsoft's Python novice tool is so delicious!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template