Metadata-Version: 2.4
Name: parsec-web
Version: 0.3.0
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
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: Programming Language :: Python :: 3.15
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable
Classifier: Programming Language :: Rust
Classifier: Topic :: Text Processing :: Markup :: HTML
License-File: LICENSE
License-File: NOTICE
Summary: A fast, spec-following HTML parser with CSS selectors and an editable tree, with a selectolax-style API.
Keywords: html,parser,html5,css-selectors,selectolax
License-Expression: Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://github.com/parsec-html/parsec/wiki/Python
Project-URL: Homepage, https://github.com/parsec-html/parsec
Project-URL: Issues, https://github.com/parsec-html/parsec/issues

# parsec-web for Python

Parsec is an HTML parser in Rust that reads pages the way a browser does,
finds what you want with CSS selectors, and lets you change the tree and
write it back out. This is its Python package, and if you've used
selectolax you already know the API:

```python
from parsec_html import HTMLParser

page = HTMLParser("<ul><li class=hit>one<li>two</ul>")
assert page.css_first("li.hit").text() == "one"
for li in page.css("li"):
    print(li.tag, li.attributes, li.html)
```

What you get over selectolax:

- **Threads.** One parsed page can be read from as many threads as you
  like, and edited from any of them. On free-threaded Python (3.14t
  and later) the module runs with the GIL off, and on any Python, parsing and
  `css()` let go of it while they work.
- **Selectors selectolax 1.0.2 won't run**: `:lang()`, `:dir()`,
  `:valid`, `:in-range`, `:scope` and more, which it rejects as
  unparseable, and `:target` and `:local-link` once you pass the page's
  `url`.
- **Limits** for pages you don't trust: `budget=` (seconds) and
  `max_depth=` when you parse, and `max_steps=` and `budget=` on `css()`
  and the other selector calls, so a hostile `:has()` can't hold a worker
  for minutes. A limit that runs out raises `TimeoutError`; you never get
  half the matches.

  ```python
  page.css("div:has(span div)", max_steps=10_000_000, budget=0.5)
  ```
- **Nodes that outlive edits.** A removed node can still be read, and put
  back.
- **XPath 1.0**, which selectolax doesn't have. `xpath()` gives back what
  lxml's does, so code written for lxml or parsel reads the same:

  ```python
  page.xpath("//li/text()")              # ['one', 'two']
  page.xpath("count(//li)")              # 2.0
  page.xpath("//a[@rel=$r]/@href", r="next")
  ```

  Elements and comments come back as nodes, text and attribute values as
  `str`, and a number, string or boolean as `float`, `str` or `bool`.
  One place they part: a number turned into a string follows XPath 1.0
  here, shortest digits and never an exponent. So `string(0.1 + 0.2)` is
  `'0.30000000000000004'`, where lxml rounds to 15 digits and says `'0.3'`,
  and 10<sup>16</sup> comes out as `'10000000000000000'`, not `'1e+16'`.
- **Where everything was written.** Parse with `positions=True` and every
  node knows its place in your input: `node.source_range` and
  `node.end_tag_range` are `(start, end)` indexes into what you passed
  (code points into a `str`, bytes into `bytes`), so `src[start:end]` is
  the tag as you wrote it; `node.position` is
  its `(line, column)`, and `node.attribute_range("href")` finds one
  attribute.
- **Parse errors.** With `errors=True`, `page.errors` lists each one with
  the HTML Standard's name for it and where it is:
  `2:1: unexpected-end-tag`.
- **Bytes in any encoding.** Hand `HTMLParser` the `bytes` you
  downloaded and it decodes them as a browser would: a byte order mark
  first, then the HTTP `charset`, which you pass as `transport_encoding`,
  then a `<meta>`, then UTF-8 if the bytes are valid UTF-8, then
  `default_encoding` (windows-1252 unless you say otherwise;
  `encoding_for_locale("ja")` gives the one a Japanese browser uses). `page.encoding` says which it was, and
  `page.encoding_confidence` whether it's `"certain"` or `"tentative"`.
  Positions stay byte offsets into your bytes, whatever the encoding.

  ```python
  with urllib.request.urlopen(url) as r:
      page = HTMLParser(r.read(), transport_encoding=r.headers.get_content_charset())
  page.encoding        # 'Shift_JIS'
  ```

  A `charset` that names no encoding is passed over, as browsers pass
  it over.

  `StreamParser` does the same as the bytes arrive, and you get the same
  page however they're cut:

  ```python
  with urllib.request.urlopen(url) as r:
      s = StreamParser(transport_encoding=r.headers.get_content_charset())
      while chunk := r.read(65536):
          s.feed(chunk)
  page = s.close()     # an HTMLParser
  ```

  The names are those of lxml's feed parser and the standard library's
  `html.parser`; the keywords are html5lib's.

  **A small change.** `bytes` used to be read as UTF-8 whatever they
  were. UTF-8 still comes out as UTF-8, declared or not. Bytes that
  aren't valid UTF-8 and don't say what they are used to get U+FFFD in
  place of each bad byte; now they decode as windows-1252, as in a
  browser. Pass `transport_encoding` if you know better.
- **JavaScript.** `parsec_html.js.parse()` gives a script's ESTree, the
  tree acorn and ESLint use, as dicts and lists; `module=True` parses a
  module. `start` and `end` are indexes into your `str`. A syntax error
  raises `JSSyntaxError`, a `ValueError` with `code`, `line`, `column`,
  `start`, `end` and the `frame` a compiler would print:

  ```python
  from parsec_html import js

  tree = js.parse("export const a = [1, 2];", module=True)
  tree["body"][0]["declaration"]["declarations"][0]["init"]["type"]   # 'ArrayExpression'
  try:
      js.parse("let x = ;")
  except js.JSSyntaxError as e:
      print(e.frame)
  ```

  `max_depth=` (at most and by default 256) and `max_steps=` bound a
  script you don't trust: too deep raises `JSSyntaxError` with the code
  `too-deep`, and past the steps, `TimeoutError`.
- **The state pages keep in scripts**, read without running anything:
  `window.__NUXT__ = …`, a top-level `var ytInitialData = …`,
  `JSON.parse("…")`, Nuxt 2's function form and Next.js's
  `self.__next_f` pushes. `page.page_state()` reads every inline script
  on a page; `js.page_state(source)` reads one.

  ```python
  page = HTMLParser(html)
  for found in page.page_state():
      print(found["name"], found.get("value", found.get("error")))
  ```

  Each is `{"name", "value"}`, or `{"name", "error": {"code", "source"}}`
  when the value would need code to run, like `window.x = f()`.

## Installing

```sh
pip install parsec-web
```

The package was `parsec-html` up to 0.2. The module is still
`parsec_html`, so moving up changes nothing in your code.

There are wheels for CPython 3.10 and newer, free-threaded too, on Linux
(glibc and musl), macOS and Windows, x86-64 and ARM. Anywhere else, pip
builds the sdist, which needs Rust 1.88 or newer. The newest code on
`main` installs the same way from git:

```sh
pip install "git+https://github.com/parsec-html/parsec#subdirectory=bindings/python"
```

## Moving from selectolax

Change the import, and most code runs as it was:

```python
# from selectolax.lexbor import LexborHTMLParser as HTMLParser
from parsec_html import HTMLParser
```

`HTMLParser(html, is_fragment=False, fragment_tag="div",
fragment_namespace="html", scripting=False)` takes what
`LexborHTMLParser` does (plus `budget`, `max_depth`, `url`, `positions`,
`errors`, `transport_encoding` and `default_encoding`), and the parser and its nodes have selectolax's
names: `root`, `head`, `body`, `html`, `css`, `css_first` (with `default`
and `strict`), `css_matches`, `any_css_matches`, `tags`, `text(deep,
separator, strip, skip_empty)`, `merge_text_nodes`, `strip_tags`,
`unwrap_tags`, `create_node`; on a node also `tag`, `id`, `attributes`,
`attrs`, `inner_html` (which you can set), `text_content`,
`comment_content`, `parent`, `next`, `prev`, `first_child`, `last_child`,
`iter`, `traverse`, `decompose`, `remove`, `unwrap`, `replace_with`,
`insert_before`, `insert_after`, `insert_child` (all four taking a string
as text, or a node to copy, or to move with `move=True`), and the
`is_*_node` checks.

Where it behaves differently:

| | selectolax 1.0.2 | parsec_html |
|---|---|---|
| `<a href>`'s `attributes` | `{'href': None}` | `{'href': ''}`: Parsec doesn't yet record whether a value was written |
| A selector that doesn't parse | `SelectolaxError` | `SelectorError`, a `ValueError` |
| A node after `decompose()` | freed | reads as empty (no parent, children, attributes or text, `html` is `""`, no selector matches) but keeps its `tag`; `xpath()` and putting it back raise `ValueError` |
| `remove()` | the same as `decompose()` | takes the node out but keeps it readable, to put back with `move=True` |
| `root.decompose()` | `SelectolaxError` | decomposes `<html>`; only the document node itself raises `ValueError` |
| `attrs.items()`, `keys()`, `values()` | iterators | lists |
| `bytes` in | UTF-8, or sniffed with `encoding=True` | sniffed as a browser sniffs them: byte order mark, `transport_encoding`, `<meta>`, then `default_encoding` |
| Class names | `LexborHTMLParser`, `LexborNode` | `HTMLParser`, `Node` |

Not there yet: `clone()`, `raw_html`, `raw_value`, `html_pretty`,
`inner_html_pretty`, the parser's `inner_html`, `options` and `selector`,
`select()` and its filters, `scripts_contain`, `script_srcs_contain`,
`template_fragments`, `text_lexbor`, `mem_id`, `tag_id` and the
`:lexbor-contains()` pseudo-class.

## XML

`parsec_html.xml.parse()` reads XML 1.0 with namespaces, from a `str`
or from `bytes` in the encoding they declare. It doesn't validate, and
it never fetches anything: an external DTD is left unread, and
`doc.warnings` says so.

```python
from parsec_html import xml

doc = xml.parse(open("feed.atom", "rb").read())
feed = doc.root                          # the document element
feed.namespace                           # 'http://www.w3.org/2005/Atom'
for entry in feed.children:
    if entry.kind == "element":
        print(entry.local_name, entry.attribute("href", "http://www.w3.org/1999/xlink"))
doc.xml                                  # the document, written back out
```

A node has the HTML parser's names where they mean the same thing:
`tag` (the name as written, `atom:link`), `parent`, `next`, `prev`,
`first_child`, `last_child`, `attributes`, `text()`, `source_range` and
`position`. What namespaces add is `local_name`, `prefix`, `namespace`,
`attribute(local_name, namespace)` and `attribute_list`, whose
`XMLAttribute`s carry the same four parts and the value. `kind` says
what the node is, `value` is a text, CDATA or comment node's text, and
`xml` writes a node back out, with the namespace declarations an
element alone needs.

XML that isn't well-formed raises `XMLSyntaxError`, a `ValueError`
with `code`, `message`, `line` and `column`. So does XML past its
limits, which you can tighten: `max_depth=` (2,048 unless you give
one), `max_entity_depth=` (16), and entity expansion of
`entity_allowance=` bytes (1 MiB) plus `entity_ratio=` (8) per byte of
input, which stops a billion laughs at once. `namespaces=False` reads
names as they are, colons and all. A document can't be changed, and
any number of threads can read one at once.

## Speed

`bench.py` times both on the 13 real pages `bench/` uses (24 MB in all):

| | parsec_html | selectolax | |
|---|---:|---:|---:|
| Parse all 13 pages | 66 ms | 106 ms | 1.6× |
| The 32 selectors over all 13 | 283 ms | 781 ms | 2.8× |
| Every link's `href` and text | 43 ms | 50 ms | 1.2× |

Parsec parses each of the 13 pages faster, by 1.5 to 2.8 times, and runs
each of the 32 selectors faster, by 1.04 to 29 times
(`p:nth-child(2n+1)`). The narrowest margins are the selectors that
match most of a page, such as `*` and `[class]`, where the time goes on
making a Python object per match. Medians of 20 runs on an Apple M2 Max,
CPython 3.14, at a load of 3; a second run gave the same to within 6%.

## Working on it

```sh
cd bindings/python
pip install maturin pytest
maturin develop --release
pytest tests
python bench.py   # after bench/fetch-pages.sh and pip install selectolax
```

The [Python page](https://github.com/parsec-html/parsec/wiki/Python) on
the wiki has the whole API.

