Playwright Tutorial
Playwright is an open-source project launched by Microsoft in 2020, an open-source framework for web automation and end-to-end testing.
Playwright supports multiple browsers (Chromium, Firefox, and WebKit) and multiple programming languages (JavaScript/TypeScript, Python, Java, and .NET), aiming to provide a reliable, fast, and feature-rich automated testing solution.
What basic knowledge do you need to learn Playwright?
Before learning Playwright, mastering these few things is enough:
- Know a littleJavaScript, especially
async/await; - know how to useNode.jsandnpmto run scripts;
- Understand a bit ofHTMLand selectors(such as
#id、.class); - can use the terminalto run commands.
What can Playwright do?
In one sentence: as long as a person can click it in the browser, Playwright can almost automate it.
For example:
- Click buttons
- Fill out forms
- Navigate to different pages
- Take screenshots and save web page content
Playwright Simple Example
The following is a simple Playwright example that can take a screenshot of Baidu's homepage:
Example
// hello.js
const { chromium } = require('playwright');
(async () => {
// 1. Launch browser
const browser = await chromium.launch({ headless: false }); // Set to false to see the browser
const page = await browser.newPage();
// 2. Open web page
await page.goto('https://www.baidu.com');
// 3. Take screenshot and save
await page.screenshot({ path: 'baidu.png' });
// 4. Close browser
await browser.close();
console.log("Screenshot saved to example.png");
})();
const { chromium } = require('playwright');
(async () => {
// 1. Launch browser
const browser = await chromium.launch({ headless: false }); // Set to false to see the browser
const page = await browser.newPage();
// 2. Open web page
await page.goto('https://www.baidu.com');
// 3. Take screenshot and save
await page.screenshot({ path: 'baidu.png' });
// 4. Close browser
await browser.close();
console.log("Screenshot saved to example.png");
})();
Run:
node hello.js
The browser will automatically input two todo items and save the screenshot.
Related Links
- Playwright official website:https://playwright.dev/
- Playwright open-source address:https://github.com/microsoft/playwright
- Playwright API documentation:https://playwright.dev/docs/api/class-playwright/