🎭 Playwright Advanced Actions: Becoming a Web Automation Wizard
The Big Picture: Imagine you’re a puppet master who can make things move, click, drag, and even handle secret packages (files!) on a stage (the web). Playwright gives you super powers to do things that basic clicks can’t handle!
🌟 Our Magical Analogy: The Remote-Control Robot Arm
Think of Playwright as a robot arm you control with a remote. Most of the time, you press a button and it picks something up. But sometimes you need special moves:
- Drag and Drop = Moving a toy from one box to another
- Force Option = Pushing through even when something’s blocking
- Position Option = Touching a specific spot on something
- Mouse Class = Full manual control of the arm
- File Upload = Putting a letter into a mailbox
- File Download = Catching a package that falls from the sky
🎯 1. Drag and Drop: Moving Things Around
What Is It?
Imagine you have a sticker and you want to move it from one page to another. You pick it up, carry it, and drop it somewhere new. That’s drag and drop!
How Playwright Does It
// Simple way - like magic!
await page.locator('#toy').dragTo(
page.locator('#toy-box')
);
// Step-by-step way
await page.locator('#toy').hover();
await page.mouse.down();
await page.locator('#toy-box').hover();
await page.mouse.up();
Real Example
Imagine a to-do app where you drag tasks to “Done”:
// Drag "Buy milk" to the Done column
await page.locator('[data-task="buy-milk"]')
.dragTo(page.locator('#done-column'));
Why Two Ways? The simple way works 90% of the time. The step-by-step way gives you control when things get tricky!
💪 2. Force Action Option: Pushing Through Obstacles
What Is It?
Sometimes a button is hiding behind something else, like a toy under a blanket. Normally, Playwright waits politely. With force: true, it pushes through anyway!
When You Need It
- Element covered by overlay/popup
- Element marked disabled but you know it’s okay
- Animation hasn’t finished but you can’t wait
How To Use It
// Normal click waits for element to be ready
await page.locator('#sneaky-button').click();
// Force click pushes through!
await page.locator('#sneaky-button').click({
force: true
});
Works With Many Actions
// Force check a hidden checkbox
await page.locator('#hidden-box').check({
force: true
});
// Force fill a tricky input
await page.locator('#covered-input').fill('Hello', {
force: true
});
⚠️ Warning: Only use
forcewhen you really need it! It skips safety checks, like running through a red light.
📍 3. Position Option: Clicking Exact Spots
What Is It?
Imagine a big poster. You don’t just want to touch it anywhere—you want to tap the star in the corner! Position option lets you click specific spots.
The Magic Coordinates
graph TD A[Element Box] --> B[Top-Left: 0,0] A --> C[Center: default] A --> D[Bottom-Right: width,height]
How To Use It
// Click the top-left corner
await page.locator('#big-button').click({
position: { x: 0, y: 0 }
});
// Click 50 pixels from left, 10 from top
await page.locator('#map').click({
position: { x: 50, y: 10 }
});
Real Example: Image Map
// Click on different parts of a picture
// Click the cat in the photo
await page.locator('#pet-photo').click({
position: { x: 120, y: 80 }
});
Tip: Coordinates start from the element’s top-left corner, not the page!
🖱️ 4. Mouse Class: Full Manual Control
What Is It?
Remember our robot arm? Most times you just press “grab” and it works. But page.mouse gives you the full remote control—move anywhere, click, scroll, everything!
The Mouse Commands
| Command | What It Does |
|---|---|
move(x, y) |
Move to spot on page |
down() |
Press mouse button |
up() |
Release mouse button |
click(x, y) |
Move + down + up |
wheel(dx, dy) |
Scroll the wheel |
Basic Movement
// Move mouse to coordinates
await page.mouse.move(100, 200);
// Click at a position
await page.mouse.click(100, 200);
Drawing Example
// Draw a line on a canvas!
await page.mouse.move(50, 50);
await page.mouse.down();
await page.mouse.move(200, 200);
await page.mouse.up();
// You just drew a diagonal line!
Scrolling With Mouse Wheel
// Scroll down
await page.mouse.wheel(0, 300);
// Scroll right
await page.mouse.wheel(200, 0);
When To Use: Complex drawing, custom sliders, games, or when
locatormethods aren’t enough!
📤 5. File Upload: Sending Files to Websites
What Is It?
Like putting a letter in a mailbox! When a website has an “Upload Photo” button, you need to give it a file from your computer.
The Simple Way
// Find the file input and give it a file
await page.locator('input[type="file"]')
.setInputFiles('photo.jpg');
Multiple Files
// Upload several files at once
await page.locator('input[type="file"]')
.setInputFiles([
'photo1.jpg',
'photo2.jpg',
'document.pdf'
]);
Clear Selected Files
// Oops, remove the files!
await page.locator('input[type="file"]')
.setInputFiles([]);
Tricky File Chooser Dialog
// When clicking triggers a file dialog
const fileChooser = await page
.waitForEvent('filechooser');
await page.locator('#upload-btn').click();
await fileChooser.setFiles('myfile.pdf');
Pro Tip: Use full paths for files:
/home/user/photos/cat.jpg
📥 6. File Download Handling: Catching Downloads
What Is It?
When you click “Download” on a website, a file falls into your computer. Playwright can catch that file and save it where you want!
Basic Download
// Wait for download to start
const download = await page
.waitForEvent('download');
// Click the download button
await page.locator('#download-btn').click();
// Wait for it to finish
const download = await downloadPromise;
// Save to a specific place
await download.saveAs('my-report.pdf');
Better Pattern (Promise Style)
// Start waiting BEFORE clicking
const downloadPromise = page
.waitForEvent('download');
await page.locator('#download-btn').click();
const download = await downloadPromise;
// Get the downloaded file path
const path = await download.path();
console.log('Downloaded to:', path);
Useful Download Properties
const download = await downloadPromise;
// Original filename from website
console.log(download.suggestedFilename());
// The URL it came from
console.log(download.url());
// Save with custom name
await download.saveAs('reports/Q4-2024.pdf');
Remember: Start waiting for the download before clicking the button. Otherwise, you might miss it!
🎮 Putting It All Together
Here’s a mini-adventure using all our new powers:
// Our quest: Upload avatar, drag it to
// profile, download the result
// 1. Upload a photo (force through overlay)
await page.locator('#avatar-input')
.setInputFiles('me.jpg');
// 2. Drag photo to profile area
await page.locator('#uploaded-photo')
.dragTo(page.locator('#profile-slot'));
// 3. Click save at exact position
await page.locator('#save-area').click({
position: { x: 150, y: 20 }
});
// 4. Download the final profile
const downloadPromise = page
.waitForEvent('download');
await page.locator('#export-btn').click();
const download = await downloadPromise;
await download.saveAs('my-profile.pdf');
console.log('Quest complete! 🎉');
🧠 Quick Memory Map
graph LR A[Advanced Actions] --> B[🎯 Drag & Drop] A --> C[💪 Force Option] A --> D[📍 Position Option] A --> E[🖱️ Mouse Class] A --> F[📤 File Upload] A --> G[📥 File Download] B --> B1[dragTo method] B --> B2[manual hover+down+up] C --> C1[force: true] C --> C2[skip safety checks] D --> D1[position: x,y] D --> D2[from top-left corner] E --> E1[move/click/wheel] E --> E2[down/up for drag] F --> F1[setInputFiles] F --> F2[waitForEvent filechooser] G --> G1[waitForEvent download] G --> G2[saveAs method]
🌈 You Did It!
You’ve just learned the advanced moves of Playwright:
- Drag & Drop - Move elements around like stickers
- Force - Push through obstacles when needed
- Position - Click exact spots with precision
- Mouse - Full manual control for special cases
- Upload - Send files to websites
- Download - Catch files from websites
Now you’re not just clicking buttons—you’re a web automation wizard! 🧙♂️
Next Step: Try each action on a real webpage. Practice makes perfect!