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>'

Install with pip install domq; the import name is domq too. 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().

Shape the Markdown with keyword arguments: links="reference" ([text][1] with the URLs at the end) or "footer" (a ### Links list), images="alt" or "drop", drop_data_uris=True and base_url= to make links absolute.

doc = domq.parse(html)

article = doc.main_content()               # the article without nav, ads, comments… (or None)
for chunk in (article or doc).to_markdown_chunks(1500):
    print(chunk.context, len(chunk.markdown))   # "Guide > Install" 812

meta = doc.metadata()                      # .title, .description, .canonical, .og, .json_ld, …
meta.to_dict()

for link in doc.links(base_url="https://example.com/blog/"):
    print(link.url, link.text)             # resolved, honours <base href>

rows = doc.tables("table#prices")          # [[[cell, …], …]] per table, spans expanded
csv = doc.to_csv("table#prices")

print(doc.outline().to_text())             # landmarks, headings, controls + selectors
# [1] navigation
# [2]   link "Docs" -> nav > a

sel = domq.Selector("li:nth-child(odd) > a")   # compile once, reuse
hits = [doc.select(sel) for doc in docs]

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)
to_markdown(*, links=, images=, drop_data_uris=, base_url=) Markdown with options
to_markdown_chunks(max_chars=1500, *, …) list[Chunk]: .markdown, .heading_path, .context
main_content() -> Element | None reader mode: the article's element
metadata(base_url=None) -> Metadata title, description, canonical, lang, OpenGraph, Twitter, JSON-LD, feeds (to_dict())
links(base_url=None), resources(base_url=None) list[Link] (.url, .text, .element) / list[Resource]
tables(selector="table"), to_csv(selector="table") tables as rows of cells / as CSV
outline() -> PageOutline landmarks, headings and controls (.nodes, to_text(), to_json())
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_markdown_chunks(…), to_json() this subtree as Markdown, chunks or JSON
links(), resources(), outline() the same as on Document, for this subtree
table_rows(), to_csv() this <table>'s rows / CSV
Functions and types
Selector(query) a compiled selector, accepted wherever a selector string is
resolve_url(base, relative), resolve_srcset(base, srcset) URL resolution as browsers do it
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.6.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.6.0
File Size Uploaded Provenance Actions
domq-0.6.0.tar.gz 589.2 kB With provenance Details for domq-0.6.0.tar.gz

Built distributions (wheels)

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

Total release size: 2.7 MB

Release files / domq-0.6.0.tar.gz

Download URL domq-0.6.0.tar.gz
Size 589.2 kB
Tags Source
SHA-256 checksum
How to use checksums
694beee8f96b1c51aec798959899de9e4e95f4c58899fc26e4484d34821a44ad
BLAKE2b-256 checksum
How to use checksums
d16dfb05829a5816b1a9b79242e7305724328e092638cb8ccc9c0bf93c12fe0c
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 Nov 3, 2026.

Transparency log

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

Download URL domq-0.6.0-cp311-abi3-win_amd64.whl
Size 371.1 kB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
1c9985d2afe970dc01fc7ce43deca160d13dee9bc702be98dbeecf51d1891bf3
BLAKE2b-256 checksum
How to use checksums
74f7ae5b121394ae04327506dea0ecfbb0236433d345a763d0f8d65f897ba354
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 Nov 3, 2026.

Transparency log

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

Download URL domq-0.6.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 445.1 kB
Tags CPython 3.11 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
2c9877291b6889cdb39123318cd71b6a4fd3078bff8ba0a60457a553de4314e9
BLAKE2b-256 checksum
How to use checksums
ba33297cb08b1002eac7e4f281f4731c1874e334e4a73a325085b51664124ecf
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 Nov 3, 2026.

Transparency log

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

Download URL domq-0.6.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 424.1 kB
Tags CPython 3.11 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
7e92e1d8d6988aeb8a25286707f342070f48a57d749dddfbed2a8680e5803aba
BLAKE2b-256 checksum
How to use checksums
c5fe9a16592464dc64eba1905d1fda6e6d437ec2ded2e6860645eca3f63257d7
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 Nov 3, 2026.

Transparency log

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

Download URL domq-0.6.0-cp311-abi3-macosx_11_0_arm64.whl
Size 413.2 kB
Tags CPython 3.11 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
3add18e70620e3fc81613567b21ffcdabc7d84c0969105009e064cb00f01478e
BLAKE2b-256 checksum
How to use checksums
ba184bfc2371758e3f88fd5884a1e73024464b65ba021f5cb1f2601d18042a59
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 Nov 3, 2026.

Transparency log

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

Download URL domq-0.6.0-cp311-abi3-macosx_10_12_x86_64.whl
Size 429.4 kB
Tags CPython 3.11 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
50d1b4d05de35a990652c863d0281925daa3302ce4b0b323916667d3dde43989
BLAKE2b-256 checksum
How to use checksums
f9aa79e55e50537963680a838079bd5369654ac569465484802981d7a5788478
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 Nov 3, 2026.

Transparency log

Security for domq 0.6.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.6.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 Nov 3, 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.

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