Query¶
Search a tree with the methods on Node: find() and find_all() walk an Axis
with attribute filters, select() and select_one() take CSS selectors, and xpath(),
xpath_iter(), and xpath_one() evaluate XPath. With smart_strings=True an XPath string result
comes back as an XPathString that remembers the element it was selected from. XPath compiles an
expression once and evaluates it against many context nodes or documents, skipping the per-call parse.
- class turbohtml.Axis(*values)¶
The direction find()/find_all() walk from a node, passed as their axis argument.
DESCENDANTS visits every node in the subtree in document order (the default); CHILDREN only the direct children; ANCESTORS the parent chain up to the document; NEXT_SIBLINGS the following siblings and PREVIOUS_SIBLINGS the preceding ones; FOLLOWING every node after this one in document order (skipping its descendants) and PRECEDING every node before it (skipping its ancestors).
- DESCENDANTS = 0¶
- CHILDREN = 1¶
- ANCESTORS = 2¶
- NEXT_SIBLINGS = 3¶
- PREVIOUS_SIBLINGS = 4¶
- FOLLOWING = 5¶
- PRECEDING = 6¶
- class turbohtml.XPathString(value: str, parent: Element, is_attribute: bool, attrname: str | None)¶
A string xpath result that remembers the element it came from.
- Parameters:
value – the string value itself, the attribute or
text()result.parent – the element the value was selected from, returned by
getparent().is_attribute (
bool) – whether the value came from an attribute rather than element text.attrname (
str|None) – the attribute name the value came from, orNonefor a text value.
- class turbohtml.XPath(expression: str, /, *, smart_strings: bool = ..., extensions: dict[tuple[str | None, str], Callable[..., str | float | bool]] | None = ...)¶
A precompiled XPath 1.0 expression, parsed once and evaluated against many context nodes. Call it with a context Node and optional $name keyword variables: XPath(“//td[@class=$cls]”)(row, cls=”num”). It returns the same results as Node.xpath. smart_strings and the extensions dict are bound here at construction. The object is immutable and re-entrant, so one instance can be shared across threads.
- Raises:
TypeError – expression is not a str, a variable binding is of an unsupported type, or a value is used where a node-set is required.
ValueError – the expression is not valid XPath (with the offending token and its offset), nests past the depth limit, calls an unknown or wrong-arity function, or references an unbound variable or prefix.
Every selector-parse path – select(), matches(), closest(), the
turbohtml.query matching helpers, and turbohtml.convert.css_to_xpath() – raises this one error on a
malformed selector. It subclasses ValueError, so code catching ValueError keeps working.
- exception turbohtml.SelectorSyntaxError¶
A CSS selector could not be parsed.
Raised by
select(),matches(), andclosest(), by theturbohtml.querymatching helpers, and byturbohtml.convert.css_to_xpath(). It subclassesValueError, so code catchingValueErrorkeeps working while a soupsieve port can catch it by its soupsieve name.
turbohtml.query¶
The turbohtml.query namespace adds two optional facades over the CSS and XPath engines the node methods above
already expose: a pyquery-style chainable Query, and a soupsieve-shaped matching surface for a BeautifulSoup
port. Both run the same native engine as the node methods; neither is a second engine.
Chainable queries¶
A pyquery-style fluent, chainable query wrapper over the tree and selector engine, for code migrating off pyquery’s
jQuery-style chaining. Each traversal and mutation method returns a Query, so calls compose.
- class turbohtml.query.Query(source)¶
An ordered, duplicate-free set of elements with chainable traversal and mutation.
- Parameters:
source (
str|Element|Document|Iterable[Element]) – HTML to parse, a single Element or Document, or an iterable of Elements.
- __call__(selector)¶
Select the descendants of the wrapped elements matching a selector, like
find.
- find(selector)¶
Select every descendant of the wrapped elements matching a selector.
- filter(selector)¶
Keep the wrapped elements that themselves match a selector.
- eq(index)¶
Reduce the set to the element at one index.
- parent()¶
Select the immediate parent of each wrapped element.
- Return type:
- Returns:
a query over the parent elements.
- children(selector=None)¶
Select the element children of each wrapped element.
- siblings(selector=None)¶
Select the sibling elements of each wrapped element.
- closest(selector)¶
Select the nearest self-or-ancestor of each wrapped element matching a selector.
- items()¶
Iterate the wrapped elements, each as its own single-element query.
- attr(name, value=None)¶
- Overloads:
self, name (str) → str | None
self, name (str), value (str) → Query
Get an attribute from the first element, or set it on every element.
- text(value=None)¶
- Overloads:
self → str
self, value (str) → Query
Get the combined text of every element, or set each element’s text.
- html()¶
Return the inner HTML of the first element.
- has_class(name)¶
Test the wrapped elements for a class.
- add_class(name)¶
Add a class to every wrapped element.
- remove_class(name)¶
Remove a class from every wrapped element.
Soupsieve-shaped matching¶
A soupsieve-shaped CSS matching surface over turbohtml’s native selector
engine, for code migrating off soupsieve (BeautifulSoup’s selector library) or a bs4 Tag.select stack.
compile() returns a reusable Matcher carrying soupsieve’s matcher methods, and the module-level
select()/select_one()/iselect()/match()/filter()/closest() helpers compile a
one-shot matcher per call. Every entry point runs the same engine as select()/
matches()/closest(), so the matching is identical to the node methods –
this surface only adds the soupsieve call shapes.
It is a pure-Python facade with no second engine. The selector entry points on the C core take only the selector string,
so soupsieve’s namespaces and flags arguments are bundled into one immutable Matching config that
travels with the matcher for API parity. Neither alters which elements match: turbohtml selects by an element’s local
name, so a prefixed type selector such as svg|rect matches every rect regardless of the namespaces map, and
flags is advisory exactly as in soupsieve. Namespace-discriminating selection is a tracked engine gap, not part of
this surface.
- turbohtml.query.compile(selector, options=None, /)¶
Compile a CSS selector into a reusable
Matcher, likesoupsieve.compile.The selector is validated up front, so a malformed one raises
turbohtml.SelectorSyntaxErrorhere, not at the first match.
- turbohtml.query.css(selector, options=None, /)¶
Compile a CSS selector into a
Matcher; a readable alias ofcompile().
- class turbohtml.query.Matcher(selector, options=None, /)¶
A selector compiled against turbohtml’s engine, with the soupsieve matcher methods.
Build one with
compile()and reuse it; it is immutable and thread-safe. Each method runs the native selector engine over the node passed in, so oneMatcherserves many trees.- Parameters:
selector (
str) – the CSS selector; validated immediately, raisingturbohtml.SelectorSyntaxErrorwhen malformed.options (
Matching|None) – theMatchingconfig, orNonefor soupsieve’s defaults.
- property namespaces: Mapping[str, str] | None¶
The configured namespace map, named as soupsieve’s
SoupSieve.namespaces.
- match(node)¶
Test whether one element matches the selector.
- select(node, limit=0)¶
Collect the descendants of an element that match the selector, in document order.
- select_one(node)¶
Return the first descendant of an element that matches the selector.
- iselect(node, limit=0)¶
Iterate the descendants of an element that match the selector, in document order.
- filter(iterable)¶
Keep the members of an iterable that match the selector.
Module-level helpers¶
Each helper compiles the selector for the single call and delegates to the matching Matcher method, mirroring
soupsieve’s free functions. Reuse a compile() result instead when matching the same selector repeatedly.
- turbohtml.query.select(selector, node, options=None, /, *, limit=0)¶
Collect the descendants of an element matching a selector, compiling it for this one call.
- Parameters:
- Return type:
- Returns:
the matching descendants in document order.
- turbohtml.query.select_one(selector, node, options=None, /)¶
Return the first descendant of an element matching a selector, compiling it for this one call.
- turbohtml.query.iselect(selector, node, options=None, /, *, limit=0)¶
Iterate the descendants of an element matching a selector, compiling it for this one call.
- Parameters:
- Return type:
- Returns:
an iterator over the matching descendants.
- turbohtml.query.match(selector, node, options=None, /)¶
Test whether an element matches a selector, compiling it for this one call.
- turbohtml.query.filter(selector, iterable, options=None, /)¶
Keep the members of an iterable matching a selector, compiling it for this one call.
- Parameters:
- Return type:
- Returns:
the members that match.
- turbohtml.query.closest(selector, node, options=None, /)¶
Return the nearest self-or-ancestor of an element matching a selector, compiling it for this one call.
Configuration¶
- class turbohtml.query.Matching(namespaces=None, flags=0)¶
The soupsieve
namespacesandflagsarguments, bundled into one immutable, thread-safe config.Pass it as the
optionsofcompile()(or any module-level helper) to mirror a soupsieve call. Both fields are carried for API parity and do not change which elements match: turbohtml selects by an element’s local name, so a prefixed type selector (svg|rect) matches everyrectregardless of thenamespacesmapping, andflagsis advisory as in soupsieve.Matching()reproduces soupsieve’s default HTML matching.- Parameters:
namespaces (
Mapping[str,str] |None) – prefix-to-URI map for prefixed type selectors, accepted for soupsieve parity; the native engine does not discriminate by namespace URI (see the module reference).flags (
int) – the soupsieve flag bitmask (onlyDEBUGis defined); accepted and carried but inert.
- classmethod soupsieve(namespaces=None, flags=0)¶
Build a config straight from soupsieve’s
(namespaces, flags)call convention.Lets a port keep the original argument list –
Matching.soupsieve(namespaces=ns, flags=DEBUG)– rather than renaming keywords at every call site.
- turbohtml.query.DEBUG = 1¶
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int(‘0b100’, base=0) 4
A malformed selector raises turbohtml.SelectorSyntaxError, the one error every selector-parse path shares.
- turbohtml.query.escape_identifier(ident)¶
Escape a string so it is a valid CSS identifier, like
soupsieve.escape/CSS.escape.Useful for building a selector around a class or id read from data:
f"#{escape_identifier(raw_id)}"is safe even whenraw_idstarts with a digit or holds./#/spaces.