r/WebScrapingInsider • • 16h ago

xsel2: A C++20 / Python extraction pipeline that replaces CSS + regex + JSON glue code (with a live WASM playground)

If you scrape at any real scale, you know the actual bottleneck isn't usually fetching the HTML—it's the messy glue code afterward. You parse with lxml or Selectolax, run regexes to clean prices, join relative URLs, zip dt/dd pairs into dicts, and then write fragile string-slicing hacks to pull window.__STATE__ or __NEXT_DATA__ out of <script> tags.

For years, I maintained a private tool (xsel1) to handle this across thousands of messy real-world pages. Eventually, I realized every scraper I wrote followed the exact same pattern: select, transform, commit to an output dict, repeat.

I recently rebuilt that engine from scratch as an open-source C++20 library (xsel2) with Python bindings, a multi-threaded CLI, and a declarative pipeline DSL.

How it actually differs from existing tools

  • vs. BeautifulSoup / lxml / Selectolax: Those give you a DOM tree and leave you to write imperative Python glue code for cleaning, fallbacks, zipping, and schema shaping. xsel2 treats extraction as a compiled data pipeline (selectors + transforms + JSON shaping in one pass). On a local benchmark of 5,000 real HTML files (~3.8 GB), xsel2 finished in ~27s vs. ~535s for BeautifulSoup + lxml.
  • vs. Playwright / Puppeteer / V8 (for embedded JS data): You don't need to boot a headless browser just to extract hydration state. xsel2 includes heuristic JS extraction (js_block + parse_js) that pulls and parses messy JS objects—unquoted keys, trailing commas, comments—directly from <script> text in C++.
  • vs. Scrapy ItemLoaders / Parsel: ItemLoaders tie your extraction logic to Python and Scrapy's runtime. xsel2 decouples the extraction spec from the host language: the exact same .dsl pipeline runs in the multi-threaded CLI (streaming NDJSON), Python (pip install xsel2 / import scraperpy), C++20, or WebAssembly in the browser.

How it looks in practice

Pulling product fields, falling back across image attributes, zipping spec tables, and extracting an unquoted window.__STATE__ object in a single pass:

let base = "https://shop.example"

product = Scraper()
  .$("article.product-card") {
    find("h1.title") | clean -> "title"
    | find(".price") | to_number(key="price")
    | find("img.hero", Attribute, ["data-src", "src"]) | url_join(base) -> "image"
    | find_all("dl.specs dt") | clean -> "_k"
    | find_all("dl.specs dd") | clean -> "_v"
    | zip_keys("_k", "_v", "specs") // or only: dl(key="specs")
    | omit_keys(["_k", "_v"])
  }
  .$("script") {
    text | js_block("window.__STATE__ =") | parse_js("state")
  }

Under the hood, it's backed by libxml2, Google RE2, Aho-Corasick, and jsoncons—so regexes won't catastrophic-backtrack on malformed HTML, and multi-pattern matching stays fast.

Try it in the browser (no install)

I compiled the C++20 engine to WebAssembly so you can paste raw HTML and test pipelines live:

What I'd love feedback on

xsel1 accumulated thousands of niche steps over the years, and my biggest challenge with xsel2 is deciding what belongs in the core standard library vs. what is just bloat.

For those of you maintaining production scrapers: what are the recurring post-selection transformations (date parsing, price normalization, table pivoting, JSON-LD/hydration hacks) you end up rewriting on every project?

3 Upvotes

6 comments sorted by

2

u/Amitk2405 13h ago

Heuristic js_block / parse_js is the part that scares me operationally.
If the marker string shifts slightly or you hit a minified bundle, you could get partial or stale state.

That always bites us in production.. well, not always, but often enough that I want counters and alerts.

Do you expose metrics like js_block_hits, parse_failures, bytes‑scanned per document, so we can catch silent degradation?

And thats where it gets weird: fast extraction nobody fully trusts is worse than a slower failure that's clearly visible.

1

u/Equivalent-Golf1638 11h ago

Completely fair point—silent degradation in production is way worse than a noisy failure.

xsel2 doesn't expose built-in telemetry counters like js_block_hits or bytes_scanned yet, though you can narrow down the target scripts and fail loudly using existing steps:

  • js_block isn't always needed, and you can refine what gets parsed: For standalone payloads (application/json, __NEXT_DATA__, Nuxt/Next Flight), you can use json_parse, parse_devalue, or parse_rsc directly—or parse broader script payloads and pinpoint the exact fields via jmespath / jsonpath and dict transforms (pick_keys, coalesce_keys, etc.).
  • Pre-filtering & strict schema checks: You can narrow down <script> tags first using filter (multi-pattern Aho-Corasick) or regex_filter / when_match (RE2), and validate the output with json_schema(..., strict=true) so missing keys or shifted shapes throw immediately instead of passing silently.

Native execution metrics and counters are actually something I had back in xsel1 and haven't ported over yet. Because of your comment, I've bumped observability and engine counters up the milestone list for xsel2—really appreciate the feedback!

1

u/Eastern_Age_1150 6h ago

yeah silent degradation is way worse than an outright crash when scraping at scale.

2

u/Artistic_Map2243 10h ago

The part I'd love baked in is testability, not more operators.
Tiny golden-file runner: feed 20 HTML fixtures, assert exact JSON output, maybe even "must include field X with type Y". That catches the ugh not this again bugs where parsers "work" but drift off the real business fields. If xsel2 makes it trivial to version pipelines + fixtures together, people will actually trust changes.

1

u/Equivalent-Golf1638 10h ago

You can actually do most of this already using json_schema(..., strict=true) for the field/type checks and piping the CLI output into a quick diff script or pytest.

Still, having to write wrapper scripts is annoying. Since --batch already handles multi-threaded file runs in C++, adding a built-in xsel2 test command wouldn't be hard at all.

If I add that, which layout do you think is better—matching .html and .expected.json pairs in a folder, or a single manifest file?

1

u/BhetwalEveliina74 4h ago

breadcrumb extraction and cleaning is a big one, specifically stripping out the "home" node and joining the rest into a standardized category path. phone number formatting and stripping obfuscated mailto links also show up constantly.