Playwright Browser Automation
by @onlyloveher
Browser automation using Playwright API directly. Navigate websites, interact with elements, extract data, take screenshots, generate PDFs, record videos, an...
const { chromium } = require('playwright');(async () => {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({ path: 'screenshot.png' });
await browser.close();
})();
1. Use Locators (Auto-waiting)
// β
GOOD: Uses auto-waiting and retries
await page.getByRole('button', { name: 'Submit' }).click();
await page.getByLabel('Username').fill('user');
await page.getByPlaceholder('Search').fill('query');// β BAD: May fail if element not ready
await page.click('#submit');
2. Prefer User-Facing Attributes
// β
GOOD: Resilient to DOM changes
await page.getByRole('heading', { name: 'Welcome' });
await page.getByText('Sign in');
await page.getByTestId('login-button');// β BAD: Brittle CSS selectors
await page.click('.btn-primary > div:nth-child(2)');
3. Handle Dynamic Content
// Wait for network idle
await page.goto('https://spa-app.com', { waitUntil: 'networkidle' });// Wait for specific element
await page.waitForSelector('.results-loaded');
await page.waitForFunction(() => document.querySelectorAll('.item').length > 0);
4. Use Contexts for Isolation
// Each context = isolated session (cookies, storage)
const context = await browser.newContext();
const page = await context.newPage();// Multiple pages in one context
const page2 = await context.newPage();
5. Network Interception
// Mock API responses
await page.route('**/api/users', route => {
route.fulfill({
status: 200,
body: JSON.stringify({ users: [] })
});
});// Block resources
await page.route('**/*.{png,jpg,css}', route => route.abort());
clawhub install playwright-automation-v1