Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Node.js, a CSS selector is a string that identifies elements in a document, such as article h2 or [data-kind="note"]. With Cheerio, load HTML and pass the selector to its $ function; with Puppeteer, pass it to a browser page locator. The selector finds elements in the document you give it—it does not fetch a page or run JavaScript by itself.

Choose the document context before writing a selector

Scraping with selectors has two separate jobs: obtain the document, then find the elements that contain the fields you need. A selector only handles the second job. If you already have HTML, Cheerio can parse it without driving a browser. If the page’s content appears only after browser-side execution, a browser-backed workflow such as Puppeteer may be necessary.

Approach What the selector queries Use it when
Cheerio HTML loaded into Cheerio You have markup to parse and want to select and extract nodes without querying a live browser page. See the Cheerio selecting guide.
Puppeteer The page exposed through a browser Your workflow needs a browser page. Puppeteer’s Page.locator() accepts CSS selectors, as well as additional locator syntax. The official API reference showed Puppeteer version 25.12.0 when accessed on September 29, 2026: Page.locator().

Neither choice makes selectors responsible for navigation, data acquisition, pagination, access permissions, or site policy. Decide how to obtain the page separately from how to match its elements.

Select and extract HTML with Cheerio

Install Cheerio in a Node.js project with npm install cheerio. The following complete example reads a local HTML file, selects article cards, and extracts each card’s heading, link, and summary. It expects markup containing article.card, a heading link inside each card, and an element with class summary; change the selectors to match the HTML you actually have.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • 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.
const fs = require('node:fs/promises');
const cheerio = require('cheerio');

async function main() {
  const html = await fs.readFile('page.html', 'utf8');
  const $ = cheerio.load(html);

  const records = $('article.card').map((_, card) => {
    const item = $(card);
    const titleLink = item.find('h2 a').first();

    return {
      title: titleLink.text().trim(),
      href: titleLink.attr('href') ?? null,
      summary: item.find('.summary').text().trim()
    };
  }).get();

  console.log(JSON.stringify(records, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Save the markup as page.html and run the file with Node.js. The result is an array of records. text() reads text from the selected nodes, attr('href') reads an attribute, map() processes the matched cards, and get() returns the mapped values as a regular array. Selection and extraction are distinct: choosing article.card does not automatically create a record or decide which fields belong in it.

Start with a small, verifiable selector

Inspect the HTML you loaded and find a distinctive tag, class, ID, or attribute. Begin with the shortest selector that identifies the intended elements, then check how many results it returns. For example:

console.log('cards:', $('article.card').length);
console.log('first title:', $('article.card h2').first().text().trim());

These checks help distinguish a selector that is syntactically valid but does not match the document from one that matches more elements than intended. Do not assume a class or attribute is stable across site redesigns: confirm it against the markup you are scraping.

Use CSS selector syntax to describe what you want

Cheerio supports familiar CSS selector forms, including tags, classes, IDs, attributes, and relationships between elements. The selector examples below follow the Cheerio selecting guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 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.
Goal Selector in Cheerio What it matches
Every paragraph $('p') Elements named p.
A class $('.selected') Elements carrying the selected class.
An ID $('#main') The element with the main ID.
An attribute value $('[data-selected="true"]') Elements with data-selected set to true.
Nested headings $('article h2') h2 elements anywhere inside an article.
Direct child headings $('article > h2') h2 elements that are direct children of an article.
Either heading level $('h1, h2') Elements matching either selector.

Descendants and direct children are different

A space means “anywhere below this element.” Thus div p can match paragraphs nested several levels inside a div. The child combinator > means “immediately inside,” so div > p excludes paragraphs inside an intervening element. Choose based on the actual tree, not on how the page looks visually.

Sibling combinators express order and shared parents

The adjacent-sibling combinator + matches the next sibling element, while the general-sibling combinator ~ matches later sibling elements under the same parent. For instance, h2 + p targets a paragraph immediately after a heading; it does not mean any paragraph somewhere below that heading.

Comma means alternatives; concatenation means requirements

h1, h2 matches either kind of heading. By contrast, p.selected requires one element to be both a paragraph and to carry the selected class. Likewise, article.card requires an article with that class.

Extract the fields your scraper needs

Once a selector identifies the right nodes, use library methods to read values. In the example, text().trim() obtains a text field, and attr('href') obtains a link attribute. If a field is optional, handle its absence explicitly rather than assuming it exists. A missing href produces null in the example.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • 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.

For repeated elements, map over the selection and return one object per match. For a single value, narrow the selection with first() when that is genuinely the intended rule. Do not use “first match” merely to hide unexpected duplicates; inspect the count and markup first. Cheerio’s guide also documents traversal methods for moving from a selected node to related nodes.

Use Puppeteer when the page context matters

Puppeteer queries a browser page rather than only the markup you loaded into Cheerio. Its current locator API accepts CSS selectors as-is, and Puppeteer also documents selectors for text, accessibility role and name, XPath, and queries that cross shadow roots. Use the API that matches the page context and your extraction task; do not assume every Puppeteer selector extension is CSS.

A browser DOM offers a related distinction: document.querySelector() returns the first matching element or null, while document.querySelectorAll() returns all matches. MDN documents these APIs and notes that invalid selector syntax passed to querySelector() raises a SyntaxError: MDN: Document.querySelector().

When a browser page has loaded the content you need, these methods query the page’s current document. They do not guarantee that a desired element has appeared or that the page’s loading sequence is complete; page timing and browser behavior are separate from selector syntax.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • 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

Keep selectors portable and valid

Standard selectors such as tags, classes, IDs, attribute selectors, combinators, and comma-separated selector lists are the safest choice when the same selector may be used in both Cheerio and browser DOM APIs. Cheerio also documents extensions including :contains(), :first, :last, and :eq(n). Its guide explicitly identifies these as nonstandard extensions; they are not valid CSS for browser APIs. Treat them as Cheerio-specific rather than assuming that a selector accepted there will work in Puppeteer’s browser page or querySelector(). See Cheerio’s selector documentation.

Characters in an ID or class may also need escaping when used in a browser CSS selector. MDN advises using CSS.escape() or suitable escaping for values that are not valid CSS identifiers. For example, a dynamically supplied identifier should not simply be interpolated into a selector without considering its characters:

const id = 'item:42';
const element = document.querySelector(`#${CSS.escape(id)}`);

This example applies in a browser context where CSS.escape() and document are available. For selector behavior and identifier escaping, see MDN: CSS selectors and MDN: Document.querySelector().

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot selectors that fail or return the wrong data

  • The result count is zero: The selector may be valid but not fit the loaded markup. Print a short excerpt of the HTML, inspect the element’s real tag, classes, and attributes, and test a simpler selector such as article before restoring the full chain.
  • You get too many matches: A descendant selector may be reaching nested content, or a class may be shared by multiple components. Narrow the selector with a parent, a direct-child combinator, or a more distinctive attribute, then check the count again.
  • A selector works in Cheerio but not in the browser: Check whether it uses a Cheerio-only extension such as :contains() or :eq(). Replace it with standard CSS or use the appropriate library-specific operation.
  • The selector throws a syntax error in a browser: Check punctuation, brackets, quotes, and dynamically inserted identifiers. Browser querySelector() throws for invalid selector syntax; escape non-standard identifier characters as described by MDN.
  • Text or attributes are empty: Confirm that the selected node actually contains the field, then inspect the relevant nested markup. A selector can match a container correctly while the extraction step targets the wrong child or attribute.
  • Cheerio does not show content visible in a browser: Verify that the HTML supplied to Cheerio contains that content. If it depends on browser execution, query a browser page instead. The selector itself does not run page scripts or acquire missing content.
  • Your records have duplicates or inconsistent fields: Check whether the outer selector matches one card per record and whether nested selectors are scoped to that card. Use the selected card as the search root, as the example does with item.find().

Performance, reliability, and scraping boundaries

This workflow makes no claim about a particular speed advantage: the right choice depends on what the task needs. Cheerio is a fit when you already have markup to parse; Puppeteer is relevant when the browser page is part of the required context. Browser execution adds a different set of workflow requirements, but the available documentation cited here does not establish a universal performance ratio.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 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.

For reliable extraction, validate the shape of your output and treat absent elements as possible data rather than silently assuming every page has every field. A selector can break when markup changes, even if it remains syntactically valid. Keep selectors readable, test them against representative input, and make failures visible through counts or field checks. Selectors do not by themselves handle pagination, network requests, site access restrictions, or permission to scrape; address those separately and follow the target site’s applicable rules.

Or skip the browser setup

If you need a screenshot or PDF rather than structured fields extracted from HTML, ScreenshotNeo offers a one-request website capture API. A screenshot is not a replacement for selecting and parsing structured values with Cheerio; it is useful when the desired output is a visual capture.

cURL example, saving a WebP capture of the target page:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. ScreenshotNeo accepts cookie or consent banners as a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for AI-agent clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Frequently Asked Questions

Can I use the same CSS selector in Cheerio and Puppeteer?

Often, if it uses standard CSS syntax. Cheerio-specific extensions such as :contains() and :eq(n) are not portable to browser DOM APIs.

Does a CSS selector fetch a web page or render JavaScript?

No. It matches elements in a document context. Fetching markup and deciding whether a browser must run page code are separate parts of a scraper.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.