Metadata-Version: 2.2
Name: xsel2
Version: 0.7.0
Summary: High-performance HTML/XML scraping, multi-pattern text search, and JSON transformation engine
Keywords: scraping,html,xml,css,xpath,json,jmespath,jsonpath,aho-corasick
Author: MateusGPe
License: MIT
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Text Processing :: Markup :: HTML
Classifier: Topic :: Text Processing :: Markup :: XML
Classifier: Typing :: Typed
Project-URL: Homepage, https://mateusgpe.github.io/xsel2
Project-URL: Documentation, https://mateusgpe.github.io/xsel2
Project-URL: Repository, https://github.com/MateusGPe/xsel2
Project-URL: Issues, https://github.com/MateusGPe/xsel2/issues
Requires-Python: >=3.9
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Description-Content-Type: text/markdown

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/MateusGPe/xsel2/main/docs/images/xsel2-banner-dark.svg" />
    <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/MateusGPe/xsel2/main/docs/images/xsel2-banner-light.svg" />
    <img alt="xsel2 — Extract clean, typed JSON from messy HTML and embedded script JS states at C++20 speed" src="https://raw.githubusercontent.com/MateusGPe/xsel2/main/docs/images/xsel2-banner-light.svg" width="100%" />
  </picture>
</p>

[![CI](https://github.com/MateusGPe/xsel2/actions/workflows/ci.yml/badge.svg)](https://github.com/MateusGPe/xsel2/actions/workflows/ci.yml)
[![Deploy Docs & WASM Playground](https://github.com/MateusGPe/xsel2/actions/workflows/deploy.yml/badge.svg)](https://github.com/MateusGPe/xsel2/actions/workflows/deploy.yml)
[![Pack & Publish scraperpy](https://github.com/MateusGPe/xsel2/actions/workflows/python-package.yml/badge.svg)](https://github.com/MateusGPe/xsel2/actions/workflows/python-package.yml)
[![PyPI](https://img.shields.io/pypi/v/xsel2)](https://pypi.org/project/xsel2/)
[![Python](https://img.shields.io/pypi/pyversions/xsel2)](https://pypi.org/project/xsel2/)
[![License: MIT](https://img.shields.io/github/license/MateusGPe/xsel2)](https://github.com/MateusGPe/xsel2/blob/main/LICENSE)

**Extract clean, typed JSON from messy HTML and embedded `<script>` JS states at C++20 speed—without a headless browser.**

`xsel2` combines `libxml2` DOM selection (CSS & XPath 1.0/3.1), heuristic JavaScript/JSON object digging, and declarative transformation pipelines into Python bindings (`scraperpy`), a multi-threaded CLI (`xsel2`), and a compiled `.dsl` language.

[![Live WASM Playground](https://img.shields.io/badge/Try_It_Live-WASM_Playground-blue?style=for-the-badge)](https://mateusgpe.github.io/xsel2/playground/)
[![Full Documentation](https://img.shields.io/badge/Read_the_Docs-xsel2_Manual-green?style=for-the-badge)](https://mateusgpe.github.io/xsel2/)

**[Try the Live WASM Playground](https://mateusgpe.github.io/xsel2/playground/) · [Read the Full Documentation](https://mateusgpe.github.io/xsel2/) · [Browse Examples](https://github.com/MateusGPe/xsel2/tree/main/examples)**

---

## 10-Second Quick Start

### Python (`scraperpy`)

```bash
pip install xsel2
```

```python
import scraperpy as sp

html = '<html><body><h1>  Mechanical Keyboard  </h1><script>window.__STATE__ = {sku: "MK-75", inStock: true};</script></body></html>'
s = sp.ScraperPy().find("h1").trim().set("title")
s.select("script").text().js_block("window.__STATE__ =").parse_js("state")
print(s.from_string(html))
```

### CLI (`xsel2`)

> **Note:** `pip install xsel2` installs the `scraperpy` Python package. To build the standalone `xsel2` CLI binary, see [Building from Source (C++20)](#building-from-source-c20) below.

```bash
# Pipe HTML from curl and extract with a CSS selector
curl -sL https://example.com | xsel2 -s "h1" -c

# Multi-threaded batch scraping to NDJSON (-j 0 auto-detects CPU threads)
xsel2 -d examples/product.dsl -n summary --batch examples/*.html -j 0
```

---

## Why `xsel2`?

| Feature | `xsel2` (`scraperpy`) | `BeautifulSoup4` | `lxml` / `parsel` |
| --- | --- | --- | --- |
| **Core Engine** | **C++20** (`libxml2` + `re2` + `jsoncons`) | Python (+ optional C parser) | C (`libxml2`) + Python |
| **CSS & XPath Support** | **CSS + XPath 1.0 & 3.1** | CSS (`soupsieve`), no XPath | CSS + XPath 1.0 |
| **Native JS `window.__STATE__` Parsing** | **Built-in JS/JSON digger** (no JS runtime) | None (manual regex + `json`) | None (manual regex + `json`) |
| **Cleaning & Transform Pipelines** | **Built-in fluent steps & `.dsl`** | Manual Python loops | Limited (`.re()` / chaining) |
| **Multi-threaded CLI Batching** | **Built-in `xsel2 --batch -j 0` (NDJSON)** | None (library only) | None (library only) |

---

## 30-Second Before vs. After

Turn real-world HTML into typed JSON in a 12-line `.dsl` pipeline (no JS runtime required):

- Clean whitespace-padded text, parse formatted prices (`$1,299.50`), and resolve lazy `data-src` / relative URLs.
- Zip `<dt>`/`<dd>` pairs into structured key-value objects.
- Extract embedded `<script>` JS objects with unquoted keys, comments, and trailing commas.

**Before (`card.html`)**

```html
<article class="product-card">
  <h1 class="title">  Mechanical   Keyboard   Pro  </h1>
  <span class="price">$1,299.50</span>
  <img class="hero" src="/img/placeholder.png" data-src="/img/mk-pro.webp" />
  <a class="manual" href="/docs/mk-pro.pdf">User Manual</a>
  <dl class="specs">
    <dt>Switch</dt><dd>Tactile Brown</dd>
    <dt>Layout</dt><dd>75% Compact</dd>
  </dl>
  <script>
    window.__STATE__ = {
      sku: "MK-75", // unquoted keys & comments
      rating: 4.8,
      inStock: true,
    };
  </script>
</article>
```

**After (`product.dsl` — 12 lines)**

```xsel2
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("a.manual", Attribute, "href") | url_join(base) -> "manual_url"
    | find_all("dl.specs dt") | clean -> "_k"
    | find_all("dl.specs dd") | clean -> "_v"
    | zip_keys("_k", "_v", "specs") | omit_keys(["_k", "_v"])
  }
  .$("script") { text | js_block("window.__STATE__ =") | parse_js("state") }
```

**Output (`xsel2 -d product.dsl -n product --html card.html`)**

```json
{
    "image": "https://shop.example/img/mk-pro.webp",
    "manual_url": "https://shop.example/docs/mk-pro.pdf",
    "price": 1299.5,
    "specs": {
        "Layout": "75% Compact",
        "Switch": "Tactile Brown"
    },
    "state": {
        "inStock": true,
        "rating": 4.8,
        "sku": "MK-75"
    },
    "title": "Mechanical Keyboard Pro"
}
```

See [`xsel2` DSL & Pipeline Steps](https://github.com/MateusGPe/xsel2/blob/main/docs/dsl-and-steps.md) for the full language and step reference.

---

## Features

- **HTML/XML Scraping & `xsel2` DSL**: CSS selector & XPath 1.0 / 3.1 extraction (`lxml2-query`, `libxml2`), HTML table & metadata extraction, fluent C++/Python pipelines, and an `xsel2` (`.dsl`) parser (`parse_dsl_string`, `load_scrapers`).
- **JS/JSON Digger**: Heuristically extracts and parses embedded JavaScript/JSON objects, comments, string concatenations, and typed scalars without executing JS.
- **Multi-Pattern & Fuzzy Algorithms**: Compressed-DFA Aho-Corasick matcher (`AhoCorasick`, `filter`, `replace`, `extract_many`) and UTF-8 Jaro-Winkler / Levenshtein fuzzy matching (`fuzzy_filter`, `similarity`).
- **JSON & CSV Queries**: JMESPath, JSONPath, JSON Schema, and CSV parsing/serialization powered by `jsoncons`.
- **Regex, Text, URL, Date & Unicode Steps**: RE2 regex filtering/replacement/extraction, RFC 3986 URL normalization, `absl::Time` date parsing, `utf8proc` Unicode normalization, and `FNV-1a 64`/`SHA-256`/Base64.

---

## Documentation

| Guide | Description |
| --- | --- |
| [Website & Interactive Docs](https://mateusgpe.github.io/xsel2/) | Full documentation site |
| [Live WASM Playground](https://mateusgpe.github.io/xsel2/playground/) | Interactive browser-based `xsel2` DSL & HTML playground |
| [Quickstart](https://github.com/MateusGPe/xsel2/blob/main/docs/quickstart.md) | Prerequisites, CMake presets, helper scripts, building, testing, and 5-minute walkthrough |
| [CLI Reference](https://github.com/MateusGPe/xsel2/blob/main/docs/cli.md) | `xsel2` CLI (single input, `stdin` pipe, and multi-threaded `--batch`) |
| [Python Bindings (`scraperpy`)](https://github.com/MateusGPe/xsel2/blob/main/docs/python.md) | `ScraperPy`, `Document`, `scrape_many`, `InsertMode`, `AhoCorasick`, `.dsl` loading, JSON queries, and `pip`/`uv` packaging |
| [`xsel2` DSL & Pipeline Steps](https://github.com/MateusGPe/xsel2/blob/main/docs/dsl-and-steps.md) | Complete `xsel2` DSL (`.dsl`) manual: syntax, sugar, execution/merge model, caveats, control flow & composition, and pipeline steps reference |
| [C++20 API Guide](https://github.com/MateusGPe/xsel2/blob/main/docs/cpp-api.md) | Embedding `scraper`, `digger`, `xsel_query`, and `xsel_common` |
| [Exhaustive Examples Index](https://github.com/MateusGPe/xsel2/blob/main/examples/EXAMPLES_INDEX.md) | Complete coverage matrix of all DSL steps, `scraperpy` methods, and `xsel2` CLI flags |
| [Examples](https://github.com/MateusGPe/xsel2/tree/main/examples) | Runnable [`sample.html`](https://github.com/MateusGPe/xsel2/blob/main/examples/sample.html), [`product.dsl`](https://github.com/MateusGPe/xsel2/blob/main/examples/product.dsl), [`scrape_example.py`](https://github.com/MateusGPe/xsel2/blob/main/examples/scrape_example.py), [`metadata.dsl`](https://github.com/MateusGPe/xsel2/blob/main/examples/metadata.dsl) / [`metadata_sample.html`](https://github.com/MateusGPe/xsel2/blob/main/examples/metadata_sample.html), [`marketplace.dsl`](https://github.com/MateusGPe/xsel2/blob/main/examples/marketplace.dsl) / [`marketplace_example.py`](https://github.com/MateusGPe/xsel2/blob/main/examples/marketplace_example.py), and complete all-steps showcase [`all_steps_showcase.dsl`](https://github.com/MateusGPe/xsel2/blob/main/examples/all_steps_showcase.dsl) / [`all_steps_showcase.py`](https://github.com/MateusGPe/xsel2/blob/main/examples/all_steps_showcase.py) |

Type stubs for `scraperpy` are provided in [`scraperpy-stubs/_scraperpy.pyi`](https://github.com/MateusGPe/xsel2/blob/main/scraperpy-stubs/_scraperpy.pyi).

---

## Building from Source (C++20)

Requires a C++20 compiler (GCC, Clang, or MSVC), CMake >= 3.24, and Python 3 dev headers. Dependencies (`jsoncons`, `pybind11`, `lxml2-query`, `abseil-cpp`, `re2`, `utf8proc`, `Catch2`) are fetched automatically via [CPM.cmake](https://github.com/MateusGPe/xsel2/blob/main/cmake/CPM.cmake). `libxml2` uses the system package if found, and falls back to fetching `GNOME/libxml2` via CPM otherwise (controlled by `-DXSEL_FETCH_LIBXML2=AUTO|ON|OFF`). XPath 3.1 (`xpath3` / `XPath3`) and AES-128-CBC (`decrypt_aes128` / `DecryptAes128`) are enabled by default via `-DXSEL_USE_XPATH3=ON|OFF` and `-DXSEL_USE_AES=ON|OFF`.

```bash
cmake --preset debug
cmake --build build -j
ctest --test-dir build --output-on-failure
```

Or run `./scripts/build_and_test.sh`. Use `--preset release` (`build-release/`) for an optimized `-O3` build. To build/install the `scraperpy` Python package via `scikit-build-core`, run `uv pip install .` (or `./scripts/pack_python.sh --clean --test`). See [Quickstart](https://github.com/MateusGPe/xsel2/blob/main/docs/quickstart.md) for install, helper scripts, and `asan-ubsan` details.

To run the repository Python examples against a local CMake build:

```bash
PYTHONPATH=build:. python3 examples/scrape_example.py
PYTHONPATH=build:. python3 examples/marketplace_example.py
PYTHONPATH=build:. python3 examples/all_steps_showcase.py
```

---

## Project Structure

- `src/common/` — Aho-Corasick, UTF-8 utilities, JSON helpers
- `src/digger/` — Tokenizer, scalar parser, and JS/JSON object digger
- `src/query/` — JMESPath and JSONPath query engine
- `src/scraper/` — Extraction pipeline, merge logic, DSL parser, and pipeline steps
- `src/cli/` — `xsel2` executable
- `src/python/` — `pybind11` bindings (`_scraperpy`)
- `scraperpy/` & `scraperpy-stubs/` — Python wrapper, `py.typed`, and `.pyi` type stubs
- `scripts/` — Build, test, and Python wheel packaging helper scripts (`build.sh`, `test.sh`, `build_and_test.sh`, `pack_python.sh`)
- `docs/` & `examples/` — User guides, API references, and runnable examples
- `tests/` — Catch2 C++ unit test suite, CMake CLI tests, and `pytest` suites (`test_python.py`, `test_cli.py`)
