Common Patterns
Common Patterns
Section titled “Common Patterns”Form Automation
Section titled “Form Automation”// Login Formawait page.goto('https://site.com/login');await page.type('#username', 'user@example.com');await page.type('#password', 'password');await page.click('button[type="submit"]');await page.waitForNavigation();
// Multi-step Formawait page.type('input[name="firstName"]', 'John');await page.type('input[name="lastName"]', 'Doe');await page.click('button.next-step');await page.waitForSelector('.step-2');await page.select('select[name="country"]', 'US');await page.click('button.submit');
Wait Strategies
Section titled “Wait Strategies”// Wait for elementawait page.waitForSelector('.content', { timeout: 10000 });
// Wait for textawait page.waitForFunction((text) => document.body.innerText.includes(text), {}, 'Welcome');
// Wait for network idleawait page.goto(url, { waitUntil: 'networkidle0' });
// Custom waitawait page.waitForTimeout(2000);
Data Extraction
Section titled “Data Extraction”// Get textconst text = await page.$eval('.title', (el) => el.textContent);
// Get multiple elementsconst items = await page.$$eval('.item', (els) => els.map((el) => ({ title: el.querySelector('.title')?.textContent, price: el.querySelector('.price')?.textContent, })),);
// Get attributesconst href = await page.$eval('a.link', (el) => el.href);
Error Handling
Section titled “Error Handling”// Retry patternasync function retryClick(selector, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { await page.click(selector); return; } catch (err) { if (i === maxRetries - 1) throw err; await page.waitForTimeout(1000); } }}
// Element existence checkconst exists = (await page.$(selector)) !== null;
Performance
Section titled “Performance”// Disable images/CSSawait page.setRequestInterception(true);page.on('request', (req) => { if (['image', 'stylesheet'].includes(req.resourceType())) { req.abort(); } else { req.continue(); }});
// Reuse sessionsconst sessionId = await createSession();// ... multiple operations ...await closeSession(sessionId);