Playwright is an open-source web automation library designed to simplify browser-based tasks and end-to-end testing. It supports multiple browsers (Chromium, Firefox, and WebKit) and programming languages, making it versatile and developer-friendly.
In this guide, we’ll explore simple to advanced Playwright scripts examples with step-by-step explanations to help you master this powerful tool.
Getting Started with Playwright:
Install Playwright:
bash
Copy
npm install playwright
-
With Playwright installed, you’re ready to start scripting.
Beginner Scripts
1. Launching a Browser and Visiting a Page
This basic script opens a Chromium browser, navigates to a webpage, and fetches the page title.
javascript
Copy
const { chromium } = require(‘playwright’);
(async () => {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.goto(‘https://example.com’);
console.log(`Page Title: ${await page.title()}`);
await browser.close();
})();
Explanation:
- chromium.launch() starts a headless browser.
- page.goto() navigates to a given URL.
- page.title() retrieves the title of the page.
2. Taking a Screenshot:
Capture a screenshot of a webpage for debugging or documentation.
javascript
Copy
const { chromium } = require(‘playwright’);
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(‘https://example.com’);
// Take a screenshot
await page.screenshot({ path: ‘screenshot.png’ });
console.log(‘Screenshot saved as screenshot.png’);
await browser.close();
})();
Key Points:
- Screenshots are saved locally using the path option.
- Useful for UI testing and reporting.
3. Filling Out and Submitting a Form:
Automate form interactions like filling fields and submitting data.
javascript
Copy
const { chromium } = require(‘playwright’);
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(‘https://example.com/login’);
// Fill in form fields
await page.fill(‘#username’, ‘testuser’);
await page.fill(‘#password’, ‘securepassword’);
await page.click(‘#submit-button’);
// Confirm submission
console.log(‘Form submitted successfully.’);
await browser.close();
})();
Explanation:
- page.fill() inputs text into form fields.
- page.click() simulates a button click.
Intermediate Scripts:
4. Handling Dropdowns
Select an option from a dropdown menu.
javascript
Copy
const { chromium } = require(‘playwright’);
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(‘https://example.com/dropdown’);
// Select an option by value
await page.selectOption(‘#dropdown-id’, ‘option-value’);
console.log(‘Option selected.’);
await browser.close();
})();
Key Functions:
- selectOption() allows you to choose options by value, label, or index.
5. Waiting for Elements
Wait for an element to appear before interacting with it.
javascript
Copy
const { chromium } = require(‘playwright’);
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(‘https://example.com’);
// Wait for a button to appear
await page.waitForSelector(‘#dynamic-button’);
await page.click(‘#dynamic-button’);
console.log(‘Button clicked after it appeared.’);
await browser.close();
})();
Why It Matters: Dynamic websites often load elements asynchronously. waitForSelector() ensures the script interacts only when the element is ready.
6. Handling Alerts:
Manage browser alerts, prompts, or confirmation dialogs.
javascript
Copy
const { chromium } = require(‘playwright’);
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(‘https://example.com/alert’);
// Handle alert dialog
page.on(‘dialog’, async dialog => {
console.log(`Alert message: ${dialog.message()}`);
await dialog.accept();
});
await page.click(‘#trigger-alert’);
await browser.close();
})();
Key Points:
- Use dialog.accept() to close alerts or confirm dialogs.
Advanced Scripts
7. Running Tests Across Browsers
Test your script on different browsers in one go.
javascript
Copy
const playwright = require(‘playwright’);
(async () => {
for (const browserType of [‘chromium’, ‘firefox’, ‘webkit’]) {
const browser = await playwright[browserType].launch();
const page = await browser.newPage();
await page.goto(‘https://example.com’);
console.log(`Testing on ${browserType}: ${await page.title()}`);
await browser.close();
}
})();
Why Use This: Ensure your application performs consistently across browsers.
8. Mocking API Responses
Test UI behavior with custom API responses.
javascript
Copy
const { chromium } = require(‘playwright’);
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.route(‘**/api/data’, route => {
route.fulfill({
status: 200,
contentType: ‘application/json’,
body: JSON.stringify({ message: ‘Mock response’ })
});
});
await page.goto(‘https://example.com’);
console.log(‘API mocked.’);
await browser.close();
})();
Use Case: Control API behavior for testing edge cases or isolating frontend issues.
9. Parallel Test Execution
Run multiple tests simultaneously to save time.
javascript
Copy
const { chromium } = require(‘playwright’);
(async () => {
const browser = await chromium.launch();
const context1 = await browser.newContext();
const context2 = await browser.newContext();
const page1 = await context1.newPage();
const page2 = await context2.newPage();
await Promise.all([
page1.goto(‘https://example.com/page1’),
page2.goto(‘https://example.com/page2’)
]);
console.log(‘Both pages loaded in parallel.’);
await browser.close();
})();
Benefit: Boost efficiency by executing scripts concurrently.
Conclusion
Playwright provides a robust toolkit for web automation, catering to both simple tasks like navigation and screenshots, and advanced workflows like API mocking and parallel testing. With the examples above, you can start small and progressively explore its full potential.
Which of these scripts will you try first? Let me know if you need additional examples or help! 😊