Playwright Tutorial
Playwright is an open-source project launched by Microsoft in 2020, an open-source framework for web automation and end-to-end (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 is needed to learn Playwright?
Before learning Playwright, mastering these few things is enough:
- Know a bit of JavaScript, especially
async/await; - Know how to use Node.js and npm to run scripts;
- Understand a bit of HTML and selectors(for example
#id、.class); - Can use the terminal to run commands.
What can Playwright do?
In a nutshell: almost anything a person can click in a browser can be automated with Playwright.
For example:
- Click the button
- Fill in forms
- Navigate to different pages
- Take screenshots and save web page content
A Simple Playwright 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 the browser
const
browser
=
await chromium.
launch
(
{
headless
:
false
}
)
;
// Set to false to see the browser
const
page
=
await browser.
newPage
(
)
;
// 2. Open a web page
await page.
goto
(
'https://www.baidu.com'
)
;
// 3. Take and save a screenshot
await page.
screenshot
(
{
path
:
'baidu.png'
}
)
;
// 4. Close the browser
await browser.
close
(
)
;
console.
log
(
"Screenshot saved to example.png"
)
;
}
)
(
)
;
Run:
node hello.js
The browser will automatically enter two to-do items and save a screenshot.
Related links
- Playwright official website:https://playwright.dev/
- Playwright open-source repository:https://github.com/microsoft/playwright
- Playwright API documentation:https://playwright.dev/docs/api/class-playwright/