Skip to main content

domq for Python

Parse messy real-world HTML, query it with CSS selectors, and get readable text or Markdown back — fast, typed, and it never chokes on bad markup. Python bindings for the domq Rust crate.

pip install domq
import domq

doc = domq.parse("<ul><li class='x'>a</li><li>b</li></ul>")
[li.text for li in doc.select("li")]   # ['a', 'b']
doc.select_first("li.x").html          # '<li class="x">a</li>'

The distribution is called domq (the name domq was taken on PyPI); the import name is domq. Wheels are abi3: one wheel per platform works on every CPython ≥ 3.11 (Linux x86_64/aarch64, macOS Intel/Apple Silicon, Windows).

Scraping

import domq
import urllib.request

html = urllib.request.urlopen("https://example.com/shop").read().decode()
doc = domq.parse(html)

products = [
    {
        "name": card.select_first(".title").text,
        "price": card.select_first(".price").text,
        "url": card.select_first("a.buy").attr("href"),
    }
    for card in doc.select("div.card")
]
# [{'name': 'Widget', 'price': '$9.99', 'url': '/buy/1'}, ...]

# Everything a selector engine should do, without a browser:
doc.select("ul > li:nth-child(odd)")
doc.select_first(".card:not(.featured) a[href^='/buy']")
doc.select_first("div:has(> h2:contains('Gadget'))")

# Navigate from any element.
price = doc.select_first("p.price")
price.parent.attrs          # {'class': 'card featured', 'data-id': '1'}
price.closest(".card")      # nearest matching ancestor (or itself)
price.parent.children       # child elements

Declarative extraction

Describe the data you want as a dataclass, one CSS selector per field, and let domq.extract fill it in. Values are converted to the field's type, lists collect every match, nested dataclasses are extracted from each matched element, and an error names the field and selector that failed.

from dataclasses import dataclass
from typing import Annotated, Optional

import domq
from domq import ExtractError, Select, extract, extract_all

@dataclass
class Review:
    author: Annotated[str, Select(".author")]
    rating: Annotated[int, Select(".stars", attr="data-rating")]

@dataclass
class Product:
    __select__ = ".product"                     # optional struct-level selector, used by extract_all
    title: Annotated[str, Select("h1")]                               # readable text (Element.text)
    price: Annotated[float, Select(".price", attr="data-value")]
    image: Annotated[Optional[str], Select("img", attr="src")]        # None when no match / attr missing
    tags: Annotated[list[str], Select(".tag")]                        # every match, document order
    reviews: Annotated[list[Review], Select(".review")]               # nested dataclass per match
    description: Annotated[str, Select(".desc", html=True)]           # inner HTML  (also outer_html=True, markdown=True)
    sku: Annotated[str, Select(attr="data-sku")]                      # no selector -> the scope element itself
    note: Annotated[str, Select(".note", default="")]                 # default when missing
    cents: Annotated[int, Select(".price", with_=lambda s: round(float(s.strip("$")) * 100))]

html = """
<div class="product" data-sku="WID-1">
  <h1>Widget</h1>
  <span class="price" data-value="9.99">$9.99</span>
  <img src="/img/widget.png" alt="Widget">
  <a class="tag">tools</a> <a class="tag">sale</a>
  <div class="desc"><p>A <b>very</b> useful widget.</p></div>
  <div class="review"><span class="author">Ann</span> <span class="stars" data-rating="5">★★★★★</span></div>
  <div class="review"><span class="author">Bob</span> <span class="stars" data-rating="4">★★★★</span></div>
</div>
<div class="product" data-sku="GAD-2">
  <h1>Gadget</h1>
  <span class="price" data-value="19.5">$19.50</span>
  <div class="desc">Does <i>gadget</i> things.</div>
  <p class="note">Back in stock soon</p>
</div>
"""

extract_all(Product, html)          # one Product per `.product`, in document order
# [Product(title='Widget',
#          price=9.99,
#          image='/img/widget.png',
#          tags=['tools', 'sale'],
#          reviews=[Review(author='Ann', rating=5), Review(author='Bob', rating=4)],
#          description='<p>A <b>very</b> useful widget.</p>',
#          sku='WID-1',
#          note='',
#          cents=999),
#  Product(title='Gadget',
#          price=19.5,
#          image=None,
#          tags=[],
#          reviews=[],
#          description='Does <i>gadget</i> things.',
#          sku='GAD-2',
#          note='Back in stock soon',
#          cents=1950)]

extract(Product, html)        # one Product: the first match of __select__
# Product(title='Widget', price=9.99, image='/img/widget.png', tags=['tools', 'sale'], ...)

doc = domq.parse(html)
extract(Product, doc.select(".product")[1])   # an Element is used as given
# Product(title='Gadget', price=19.5, image=None, tags=[], ...)

Where values come from. extract(cls, source) takes an HTML string (parsed first), a Document or an Element. For a string or Document, a __select__ on the class narrows the scope to its first match (an Element is used as given); that is the scope every selector runs in (an element's descendants, or the whole document). extract_all(cls, source) returns one cls per element matching cls.__select__, each scoped to its element. A field reads the first match's readable text unless it says attr="name", html=True (inner HTML), outer_html=True or markdown=True. Without a selector a field reads the scope itself: at document scope that is the whole document's text, HTML or Markdown (and attr= is an error, since a document has no attributes). Attr(name) / Attr(selector, name), Html(selector), OuterHtml(selector) and Markdown(selector) are shorthands for the same Select markers.

Types. str is taken as-is; int and float parse the trimmed value; bool accepts true/false in any case; a nested dataclass is extracted with the matched element as its scope; any other class is called with the string (Decimal, an Enum by value, ...). Optional[T] is None when nothing matches or the attribute is missing (a value that does not parse is still an error); list[T] is every match (possibly none); anything else is required. default= (or an ordinary dataclass default, note: Annotated[str, Select(".note")] = "") replaces a missing value, and with_= converts the source string yourself, e.g. Select("time", attr="datetime", with_=date.fromisoformat); its result is used as-is. Fields without a Select marker keep their dataclass default (and need one). Each class is analysed once and cached; from __future__ import annotations works.

Errors. Anything that goes wrong while extracting raises ExtractError (a ValueError) naming the field path, the selector and what was read:

bad = domq.parse(html.replace('data-value="9.99"', 'data-value="$5"'))
try:
    extract(Product, bad.select_first(".product"))
except ExtractError as err:
    print(err)
    # Product.price (".price" @data-value): cannot parse "$5" as float: could not convert string to float: '$5'
    err.path, err.selector, err.source
    # ('Product.price', '.price', '@data-value')

# Others look like:
# Product[1].title ("h1"): no element matches
# Product[1].price (".price" @data-value): <span> has no "data-value" attribute
# Product[0].reviews[1].rating (".stars" @data-rating): cannot parse "four" as int: invalid literal for int() with base 10: 'four'
# Typo.title ("h1:hover"): invalid selector: unsupported pseudo-class ':hover' at byte 2

A class that cannot be extracted at all (not a dataclass, a field with neither a marker nor a default, an unsupported type such as dict[str, str]) raises TypeError instead.

HTML → Markdown for LLMs and RAG

Feeding raw HTML to a model wastes tokens on markup, scripts and navigation. Pick the content you want and convert it to clean Markdown (CommonMark + GFM: headings, lists, links, images, code blocks, tables, quotes):

doc = domq.parse(html)

article = doc.select_first("article") or doc.root
markdown = article.to_markdown()
# # Release notes
#
# Version **2.0** is out. See the [docs](/docs).
#
# - Faster
# - Smaller
#
# | OS | Status |
# | --- | --- |
# | Linux | ok |

prompt = f"Summarize this page:\n\n{markdown}"

<script>, <style> and <head> never leak into the output. For plain text instead (a line per block, a blank line between paragraphs) use .text / to_text().

API

domq.parse(html: str) -> Document

Never raises on malformed HTML — the parser recovers like a browser would (implicit </p>/</li>, stray and mis-nested end tags, …) and records what it recovered from in Document.errors.

Document
select(selector) -> list[Element] every match, in document order
select_first(selector) -> Element | None the first match
to_text() / to_markdown() / to_html() the whole document as text, Markdown or HTML
to_json() -> str the tree as JSON (json.loads it)
errors -> list[tuple[int, str]] (byte_offset, message) recovery diagnostics
root -> Element | None, roots -> list[Element] the first / all top-level elements
Element
tag lower-cased tag name
attrs -> dict[str, str], attr(name, default=None) attributes (valueless ones are "")
text readable text (like to_text())
text_content raw concatenated text (DOM textContent)
html, inner_html outer / inner HTML
select(sel), select_first(sel) matching descendants
closest(sel), matches(sel) nearest matching ancestor-or-self / does it match
parent, children, document navigation
to_markdown(), to_json() this subtree as Markdown / JSON
Extraction (above)
extract(cls, source) -> cls fill a dataclass from a str, Document or Element
extract_all(cls, source) -> list[cls] one per element matching cls.__select__
Select(selector=None, *, attr=, html=, outer_html=, markdown=, default=, with_=) a field marker: Annotated[T, Select(...)]
Attr(name), Attr(selector, name), Html(sel), OuterHtml(sel), Markdown(sel) shorthand markers
ExtractError a ValueError with .path, .selector, .source, .reason

An invalid or unsupported selector raises ValueError with the reason and position (invalid selector 'a:hover': unsupported pseudo-class ':hover' at byte 1). Supported: type, .class, #id, *, attribute selectors ([a], =, ~=, |=, ^=, $=, *=, i flag), all four combinators, :nth-child()/:nth-of-type() and friends, :first-child, :only-child, :empty, :root, :scope, :not(), :is(), :where(), :has(), :contains(), :checked, :disabled, … — see the main README for the full list.

Elements keep their document alive, compare equal when they are the same node, and are hashable. Documents and elements are immutable, so they are safe to share between threads; large inputs are parsed and serialized with the GIL released, so a thread pool parses pages in parallel.

The package ships type stubs (py.typed), so editors and type checkers know every signature.

Development

cd python
python -m venv .venv && . .venv/bin/activate
pip install maturin pytest
maturin develop --release
pytest

License

MIT

Metadata

Release files for domq 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for domq 0.5.0
File Size Uploaded Provenance
domq-0.5.0.tar.gz 539.7 kB With provenance Details

Built distributions (wheels)

Table of built distributions (wheels) for domq 0.5.0
File
domq-0.5.0-cp311-abi3-win_amd64.whl CPython 3.11 abi3 Windows x86-64 Details
domq-0.5.0-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.11 abi3 Linux glibc 2.17+ x86-64 Details
domq-0.5.0-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.11 abi3 Linux glibc 2.17+ ARM64 Details
domq-0.5.0-cp311-abi3-macosx_11_0_arm64.whl CPython 3.11 abi3 macOS 11.0+ ARM64 Details
domq-0.5.0-cp311-abi3-macosx_10_12_x86_64.whl CPython 3.11 abi3 macOS 10.12+ x86-64 Details

Total release size: 2.0 MB

Release files / domq-0.5.0.tar.gz

Download URL domq-0.5.0.tar.gz
Size 539.7 kB
Tags Source
SHA-256 checksum
How to use checksums
2d075bb8809c8f6ed9a06f350afbcb0d3ab5c6f49cf93ed6402437a2438709fc
BLAKE2b-256 checksum
How to use checksums
bff90119e94805cdf2965d39235007ce9615d1821e6ee04c99657efb4d2f363f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.

Transparency log

Release files / domq-0.5.0-cp311-abi3-win_amd64.whl

Download URL domq-0.5.0-cp311-abi3-win_amd64.whl
Size 239.8 kB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
6aa90b91a93a8e94b3ce72fcf533c0492d0a4678dc1b8696e7c154d003bc3dfe
BLAKE2b-256 checksum
How to use checksums
de31ffd37d7a5acd1af6632dade737767901c1098ea76a29e4dd1c62b7ada17a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.

Transparency log

Release files / domq-0.5.0-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL domq-0.5.0-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 323.1 kB
Tags CPython 3.11 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
505e2d9de09bb0dc7d0f0b73eb6af4b0e41f85d90f1cb976d023b43df621d961
BLAKE2b-256 checksum
How to use checksums
ff2dd99edfa770fbfbfa42c1a91e75de3b10fe960235275707832d3d868f608f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.

Transparency log

Release files / domq-0.5.0-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL domq-0.5.0-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Size 309.5 kB
Tags CPython 3.11 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
3b722bbd5ea1b2e6a0eef23484ffdf58cb6901380e6997bb1101c9bc8db6c550
BLAKE2b-256 checksum
How to use checksums
f86cd88bfecead729f67216b5c41de31c8256a641921cbff000ff229775b84f3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.

Transparency log

Release files / domq-0.5.0-cp311-abi3-macosx_11_0_arm64.whl

Download URL domq-0.5.0-cp311-abi3-macosx_11_0_arm64.whl
Size 298.9 kB
Tags CPython 3.11 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
1a8af420f1970ee4f3234ee50a401863f757d305af15100ebb084443b8609f1e
BLAKE2b-256 checksum
How to use checksums
f7217da74013a80710cbcb907a0dff761ecbb18f446dacf1d442792b0eb23dc7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.

Transparency log

Release files / domq-0.5.0-cp311-abi3-macosx_10_12_x86_64.whl

Download URL domq-0.5.0-cp311-abi3-macosx_10_12_x86_64.whl
Size 311.0 kB
Tags CPython 3.11 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
0956e4ced2c0a7a6817c3364ba608d62d09294e0a9eda0c2bb8111fac0eb2396
BLAKE2b-256 checksum
How to use checksums
f02a0fd2e7972b72b82c98f680afed6b48c0aa3d3e1337a17fd10d3ac0988cf5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.

Transparency log

Security for domq 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 6 files in this release have been uploaded with provenance metadata.

Select from 6 files

Attestation for domq-0.5.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 25, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.5.0 This release

6 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page