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.7.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.7.0
File Size Uploaded Provenance Actions
domq-0.7.0.tar.gz 707.0 kB With provenance Details for domq-0.7.0.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for domq 0.7.0
File Actions
domq-0.7.0-cp311-abi3-win_amd64.whl CPython 3.11 abi3 Windows x86-64 Details for domq-0.7.0-cp311-abi3-win_amd64.whl
domq-0.7.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.7.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
domq-0.7.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl CPython 3.11 abi3 Linux glibc 2.17+ ARM64 Details for domq-0.7.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
domq-0.7.0-cp311-abi3-macosx_11_0_arm64.whl CPython 3.11 abi3 macOS 11.0+ ARM64 Details for domq-0.7.0-cp311-abi3-macosx_11_0_arm64.whl
domq-0.7.0-cp311-abi3-macosx_10_12_x86_64.whl CPython 3.11 abi3 macOS 10.12+ x86-64 Details for domq-0.7.0-cp311-abi3-macosx_10_12_x86_64.whl

Total release size: 3.1 MB

Release files / domq-0.7.0.tar.gz

Download URL domq-0.7.0.tar.gz
Size 707.0 kB
Tags Source
SHA-256 checksum
How to use checksums
940655f66fbd616094ce31349e0043cc4a5966ec645846f587e1e5cd245746ba
BLAKE2b-256 checksum
How to use checksums
b7a4772b80c2e8ee062859fbb100b0e1447fc66b1bbcdbcdac387f59f17b24f6
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 7, 2026.

Transparency log

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

Download URL domq-0.7.0-cp311-abi3-win_amd64.whl
Size 429.9 kB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
2d33b34a4bdb4fb5cfa116907c689319973719729e1bd30797ed781fc14721db
BLAKE2b-256 checksum
How to use checksums
220a99ef6a8c202eca45e1356ec3d88157f5279bca07f647faad97fc6b451741
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 7, 2026.

Transparency log

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

Download URL domq-0.7.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 500.7 kB
Tags CPython 3.11 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
8497627bab998d4b0a205f341e23d8b762d40ebbd6fb8fb456de4962ed1e6f66
BLAKE2b-256 checksum
How to use checksums
68fe53c8538586b67e028b8b1bb0c8ecacea6b9998ca2c7fa0c969ce659bcd77
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 7, 2026.

Transparency log

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

Download URL domq-0.7.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 473.3 kB
Tags CPython 3.11 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
90b2cf954e372c210b2a25d78860973458e41386bddb83a7ef989fa8bfe8958f
BLAKE2b-256 checksum
How to use checksums
263b41e4c2fb0d9dba9d4d60a462f82b589cdf849c4237af518dc7116612dcaa
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 7, 2026.

Transparency log

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

Download URL domq-0.7.0-cp311-abi3-macosx_11_0_arm64.whl
Size 461.5 kB
Tags CPython 3.11 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
15fad0e4d61d5410fdce1476a9e846c6fd8e42f02b751b6e562018b0c09194fc
BLAKE2b-256 checksum
How to use checksums
5cc0c3000cb97a08884c140735e4d9b69db2ec16eee7341af2255daaa96ca6eb
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 7, 2026.

Transparency log

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

Download URL domq-0.7.0-cp311-abi3-macosx_10_12_x86_64.whl
Size 483.1 kB
Tags CPython 3.11 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
16936702178a995545eee6a8fc4964742b440323d2968addd7d180594bf17c46
BLAKE2b-256 checksum
How to use checksums
a54ad097010db4a33cd74dc2c1700c73c3a29f8f1b4c8c9c0ddc02c1c1361e65
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 7, 2026.

Transparency log

Security for domq 0.7.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.7.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 7, 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