1. Project Setup: Create a new Node.js project. Initialize it with npm init -y. Install your chosen framework: npm install playwright or npm install puppeteer.
2. Launching a Browser: Import the library. Use playwright.chromium.launch() or puppeteer.launch() to start a browser instance. Specify headless: false to see the browser GUI for debugging.
3. Navigating to a Page: Create a new page instance: const page = await browser.newPage();. Then, navigate to a URL: await page.goto('https://example.com');.
4. Element Selection (CSS Selectors): Identify elements using CSS selectors. For example, await page.click('button#submit-button'); to click a button with ID 'submit-button', or await page.type('input[name="username"]', 'myuser'); to fill an input field.
5. Element Selection (XPath): For complex or dynamic elements, use XPath. Example: await page.click('//div[@class="product-card"]/h2[contains(text(), "Laptop")]'); to click a product title.
6. Form Filling and Clicking: Use page.type(selector, text) for text inputs and page.click(selector) for buttons, links, or checkboxes. Use page.select(selector, value) for dropdowns.
7. Waiting for Elements and Navigation: Crucially, use page.waitForSelector(selector), page.waitForNavigation(), or page.waitForTimeout(milliseconds) to ensure elements are loaded or pages fully rendered before interaction. Explicit waits prevent script failures on dynamic pages.
8. Data Extraction (Static Content): Use page.textContent(selector) or page.evaluate(() => document.querySelector(selector).innerText) to get text. For attributes: page.getAttribute(selector, 'href').
9. Data Extraction (Dynamic Content): After waiting for dynamic content to load (e.g., using page.waitForSelector), extract data as usual. For lists or tables, use page.$$eval(selector, elements => elements.map(e => e.textContent)) to extract multiple elements.
10. Session Management (Cookies): Get cookies: const cookies = await page.cookies();. Set cookies: await page.setCookie(...cookiesArray); to maintain session state across pages or restarts.
11. Session Management (Local Storage): Access local storage via page.evaluate(): await page.evaluate(() => localStorage.setItem('key', 'value')); or await page.evaluate(() => localStorage.getItem('key'));.
12. Basic Authentication: Handle HTTP basic auth by providing credentials in the URL (e.g., https://user:[email protected]) or using browser context options.
13. Closing the Browser: Always close the browser instance to free up resources: await browser.close();.