Playwright gives you one programmable browser workflow for loading pages, locating content, interacting with controls, isolating sessions, taking screenshots, and saving downloads. The examples below use the standalone Playwright library in JavaScript (not Playwright Test) and show patterns you can adapt to sites you are authorized to access. A selector, login flow, or data field is never universal: inspect the target page and confirm its terms, robots policy, authentication requirements, and rate limits first.
Install Playwright and launch a browser
Create a project, install Playwright, and download at least one browser engine.
mkdir playwright-scraper
cd playwright-scraper
npm init -y
npm install playwright
npx playwright install chromium
This standalone script launches Chromium, creates an isolated context and page, navigates to a public example page, extracts its title, and always closes the browser.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
try {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
console.log(await page.title());
console.log(await page.locator('body').innerText());
} finally {
await browser.close();
}
})();
The browser-to-context-to-page sequence follows the Page API examples in Playwright’s Page documentation. Choose a readiness condition that matches the site: domcontentloaded means the initial HTML is parsed, while data rendered later may require a locator wait or another page-specific condition.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minute#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Extract data with resilient locators
Playwright describes locators as the central piece of its auto-waiting and retry-ability. Prefer selectors that express what a user sees or what the page explicitly promises, rather than a long chain of implementation-specific CSS classes.
Use roles and accessible names first
const heading = page.getByRole('heading', { name: 'Latest articles' });
await heading.waitFor();
const articles = page.getByRole('article');
const rows = await articles.evaluateAll(items =>
items.map(item => ({
text: item.textContent?.trim() ?? '',
links: [...item.querySelectorAll('a')].map(a => ({
text: a.textContent?.trim() ?? '',
href: a.href
}))
}))
);
console.log(rows);
Other built-in choices include getByText, getByLabel, getByPlaceholder, getByAltText, getByTitle, and getByTestId. The locator guide explains when each is appropriate at playwright.dev/docs/locators.
Scope repeated controls to the correct item
If every product card has an “Add to cart” button, first filter the card by its visible product name, then find its child button. This prevents a click on the first matching button elsewhere on the page.
const product = page.getByRole('listitem').filter({ hasText: 'Product 2' });
await product.getByRole('button', { name: 'Add to cart' }).click();
CSS and XPath remain available when a semantic locator is impossible or an explicit contract requires them. Keep them short and local. A selector coupled to several nested div elements or generated class names is more likely to break when the site redesigns.
Recommended Free Tools
Wait before reading dynamic collections
locator.all() returns the matches that exist immediately; it does not wait for a changing list to finish loading. Wait for the actual readiness signal, such as a heading, a known card, or a loading indicator disappearing, then collect the list.
await page.getByRole('heading', { name: 'Results' }).waitFor();
const cards = page.getByRole('article');
const count = await cards.count();
const titles = [];
for (let i = 0; i < count; i++) {
titles.push(await cards.nth(i).getByRole('heading').innerText());
}
This is preferable to inserting an arbitrary sleep: the condition describes what “ready” means for this page.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
A complete scraping workflow
The following example visits a page, waits for article cards, extracts only the fields needed, normalizes whitespace, and writes JSON. Replace the URL and locators after inspecting your permitted target.
const { chromium } = require('playwright');
const fs = require('node:fs/promises');
(async () => {
const browser = await chromium.launch();
try {
const context = await browser.newContext({
locale: 'en-US',
userAgent: 'MyResearchBot/1.0 (contact@example.com)'
});
const page = await context.newPage();
await page.goto('https://example.com/news', {
waitUntil: 'domcontentloaded',
timeout: 30_000
});
await page.getByRole('heading', { name: 'Latest articles' }).waitFor();
const records = await page.getByRole('article').evaluateAll(items =>
items.map(item => {
const link = item.querySelector('a');
const title = item.querySelector('h2, h3');
return {
title: title?.textContent?.replace(/s+/g, ' ').trim() ?? null,
url: link?.href ?? null
};
}).filter(row => row.title && row.url)
);
await fs.writeFile('articles.json', JSON.stringify(records, null, 2));
console.log(`Saved ${records.length} records`);
} finally {
await browser.close();
}
})();
Validate required fields and deduplicate URLs in a production pipeline. If the page uses pagination, record the current page and stop condition so a rerun can resume safely. Do not assume that content visible in a browser is permission to republish it.
Automate forms, clicks, and navigation
Playwright actions wait for an element to become actionable. Use labels and roles for forms, and assert or inspect the result after each important transition.
await page.getByLabel('Search').fill('playwright');
await page.getByRole('button', { name: 'Search' }).click();
await page.getByRole('heading', { name: /Search results/i }).waitFor();
const firstResult = page.getByRole('link').filter({ hasText: 'Playwright' }).first();
console.log(await firstResult.getAttribute('href'));
When a control opens a new page or changes the URL, wait for the event or the destination condition rather than guessing a delay. If a site requires authentication, use credentials and session handling allowed by its owner; BrowserContexts isolate state but do not bypass access controls.
Isolate users and sessions with BrowserContexts
A BrowserContext is an isolated, incognito-like profile. Cookies, local storage, and other browser state are separated, and contexts are designed to be inexpensive to create. The isolation model is documented at playwright.dev/docs/browser-contexts.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
try {
const alice = await browser.newContext();
const bob = await browser.newContext();
const alicePage = await alice.newPage();
const bobPage = await bob.newPage();
await alicePage.goto('https://example.com/account');
await bobPage.goto('https://example.com/account');
// Each context has independent cookies and local storage.
await alice.close();
await bob.close();
} finally {
await browser.close();
}
})();
Use one context when a workflow must share a login across pages. Use separate contexts for separate users, tenants, or test scenarios so state does not leak between runs.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Take page and element screenshots
The stable Page API supports viewport screenshots, full-page captures, buffers, and element screenshots. See the Page API for the current options in your installed version.
await page.screenshot({ path: 'viewport.png' });
await page.screenshot({ path: 'full-page.png', fullPage: true });
const card = page.getByRole('article').first();
await card.screenshot({ path: 'first-card.png' });
const png = await page.screenshot(); // Buffer for upload or further processing
Full-page images can be large on long or continuously scrolling pages. Capture a specific element when you need a stable component image, and confirm lazy-loaded content has appeared before capturing. The forward-looking screenshots page at playwright.dev/docs/next/screenshots may describe behavior not present in your installed release, so verify version-specific options locally.
Wait for and save downloads safely
Start waiting for the download event before clicking. Then save the completed file while its context is still open. Playwright deletes files associated with a context when that context closes, so copy the file to durable storage first.
const downloadPromise = page.waitForEvent('download');
await page.getByText('Download file').click();
const download = await downloadPromise;
const suggested = download.suggestedFilename();
if (!/^[w.-]+$/.test(suggested)) {
throw new Error('Unexpected download filename');
}
await download.saveAs(`./downloads/${suggested}`);
console.log(`Saved ${suggested}`);
The event and lifecycle are documented at playwright.dev/docs/api/class-download. A click may fail to download because it opens a new tab, requires a permission, or triggers an application-specific export; inspect the page behavior rather than assuming every link emits a download.
Choose the right workflow
| Need | Recommended Playwright pattern | Important trade-off |
|---|---|---|
| Read visible content | Role, text, label, or test-id locators | Resilient when accessible names are meaningful; inspect markup when they are not. |
| Read a changing list | Wait for a page-specific readiness locator, then iterate | A fixed delay may be too short or unnecessarily slow. |
| Separate users | One BrowserContext per user or scenario | State is isolated; each context needs its own setup. |
| Save an image | page.screenshot or locator screenshot |
Full-page captures can be large and include only content rendered at capture time. |
| Save a file | waitForEvent('download'), then saveAs |
Persist the file before closing its context. |
The documentation does not establish a universal fastest locator, browser engine, or scraping success rate. Measure your own target, respect its policies, and keep concurrency and request volume appropriate.
Troubleshooting common failures
“Locator resolved to zero elements”
The accessible name, role, or page state may differ from your assumption. Inspect the rendered page, wait for a meaningful readiness locator, and check whether the content is inside a frame. Avoid immediately replacing a good semantic locator with a brittle CSS chain.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
“Strict mode violation”
Your locator matches multiple elements. Narrow it with a parent filter, an accessible name, first()/nth() when the position is intentional, or a more specific test id. Do not silently choose the first match if the wrong item would corrupt data.
Dynamic list returns incomplete data
all() does not wait for list growth. Wait for a page-specific signal, paginate deliberately, and log the number of records collected. A network-idle condition alone may be unsuitable for pages with long-lived connections.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Timeout during navigation
Check the URL, DNS, authentication, redirects, and target availability. Increase the timeout only after identifying the slow operation; use a narrower wait condition when the page continues background requests. Capture a trace or screenshot for diagnosis in your own environment.
Download disappears after the script exits
Call saveAs before closing the context or browser, and ensure the destination directory exists. Validate the suggested filename before constructing a path.
Screenshot is blank or missing content
Wait for the element that proves content is rendered, scroll or otherwise trigger lazy loading when appropriate, and check for consent dialogs, bot checks, or authentication gates. Playwright cannot guarantee access to a page or remove a site’s restrictions.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If your goal is a clean URL screenshot rather than custom browser interaction, ScreenshotNeo provides a single HTTP request. It accepts cookie/consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Read the parameter reference in the ScreenshotNeo documentation. This is a direct call; replace the URL with one you are authorized to capture.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
await Bun.write('shot.webp', res);
ScreenshotNeo also offers full-page and element capture, dark mode, device presets and custom viewports, retina scale, PDF output, HTML/CSS rendering, custom JavaScript and CSS, clicks and waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture for 100 URLs per call, a usage API, and an OpenAPI specification. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan. Sign up free for ScreenshotNeo.
Further reading and version checks
- Locators for role-first selection, filtering, and extraction.
- Best Practices for resilient user-facing locators.
- Browser contexts for isolated state.
- Locator API for collection behavior and current methods.
- Download API for event timing and file lifecycle.
Playwright documentation pages can change, and the reviewed material does not establish one stable release number for every example. Check the API reference that matches the Playwright version installed in your project before shipping.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesFrequently Asked Questions
Can Playwright scrape a site that renders data only after JavaScript runs?
Yes, Playwright drives a real browser, so you can wait for a page-specific locator after client-side rendering. It still cannot guarantee access, bypass authentication, or make republishing data permissible.
Should I use Playwright Test for a scraper?
Not necessarily. The examples here use the standalone Playwright library. Playwright Test is useful when you also need a test runner, fixtures, assertions, and reporting.
Which browser engine should I deploy?
Choose the engine that matches your target and deployment constraints, then verify behavior in your own environment. The supplied documentation does not establish a universally best engine or performance ranking.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Free tools Windows power users keep installed
One-click scans. No signup required.

