search
HomeBackend DevelopmentPython TutorialMicrosoft's Python novice tool is so delicious!

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

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

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

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

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

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()

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())

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()

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!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment