Table of Contents
1. Introduction to Playwright
2. Use Playwright to install
Recording
Sync
Asynchronous
Mobile terminal
3. Summary
Support for all browsers
Have fast and reliable execution
Has powerful automation capabilities
But it also has limitations
Home Backend Development Python Tutorial Microsoft's Python novice tool is so delicious!

Microsoft's Python novice tool is so delicious!

Apr 12, 2023 am 10:55 AM
python Microsoft Xiaobai artifact

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!

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

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

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.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

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.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

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.

See all articles