Metadata-Version: 2.4
Name: parsec-html
Version: 0.1.0
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable
Classifier: Programming Language :: Rust
Classifier: Topic :: Text Processing :: Markup :: HTML
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.9
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-html 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=`.
- **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`.
- **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.

## Installing

Parsec isn't released yet. Wheels go to PyPI as `parsec-html` with 0.1.0.
Until then, build it from git (you need Rust 1.88 or newer):

```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` |
| `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`,
`select()` and its filters, `scripts_contain`, `script_srcs_contain`,
`template_fragments`, `mem_id`, `tag_id` and the `:lexbor-contains()`
pseudo-class.

## 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.

