Convert

Translate between the query languages turbohtml speaks. css_to_xpath() turns a CSS selector list into an equivalent XPath 1.0 expression, the job cssselect does for lxml, parsel, and pyquery. The translation is a C pass over the parsed selector, and the emitted expression selects the same nodes as the selector does under turbohtml.Node.select() – including the WHATWG case-insensitive attribute set, Selectors 4 :empty, and the exact fieldset/legend rule for :disabled, where cssselect approximates. Every predicate is context-free (no bare position() tests), so the expression stays valid inside larger XPath expressions.

turbohtml.convert.css_to_xpath(selector, *, prefix='descendant-or-self::')

Translate a CSS selector list to an equivalent XPath 1.0 expression.

The XPath selects the same nodes as the selector does under turbohtml.Node.select(); a comma-separated list becomes a | union with the prefix prepended to each arm.

Parameters:
  • selector (str) – the CSS selector list to translate.

  • prefix (str) – prepended to each arm; the default scopes the expression to the context node’s subtree, matching cssselect.

Raises:
Return type:

str

Returns:

the XPath 1.0 expression.

class turbohtml.convert.GenericTranslator

A cssselect-shaped translator: css_to_xpath() is a method here, as in cssselect.

Unlike cssselect’s generic (XML) translator, the translation always follows the HTML rules turbohtml’s selector engine implements: element and attribute names are matched lowercase, and the WHATWG case-insensitive attribute set compares values case-insensitively.

css_to_xpath(css, prefix='descendant-or-self::')

Translate a CSS selector list to an equivalent XPath 1.0 expression.

Parameters:
  • css (str) – the CSS selector list to translate.

  • prefix (str) – prepended to each arm of the translated union.

Raises:
Return type:

str

Returns:

the XPath 1.0 expression.

class turbohtml.convert.HTMLTranslator(xhtml=False)

The cssselect HTMLTranslator shape.

Parameters:

xhtml (bool) – accepted for signature compatibility with cssselect; the translation applies the HTML lowercasing rules either way, because that is what turbohtml’s parser and selector engine do.

A selector the CSS grammar rejects raises turbohtml.SelectorSyntaxError (the one error every selector-parse path shares); a valid selector XPath 1.0 cannot express raises ExpressionError, under the cssselect-shaped SelectorError base.

exception turbohtml.convert.SelectorError

Parent of ExpressionError, mirroring cssselect’s error base for a valid-but-untranslatable selector.

exception turbohtml.convert.ExpressionError

The selector is valid CSS but has no XPath 1.0 equivalent (for example :dir() or *:first-of-type).