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.
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.
# 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
