### Use Translated XPath with lxml Source: https://cssselect.readthedocs.io/ Demonstrates how to use the generated XPath expression with lxml's `xpath()` method to find matching elements in an HTML document. The example shows extracting the 'id' attribute of the matched elements. ```python from lxml.etree import fromstring document = fromstring('''
text
''') [e.get('id') for e in document.xpath(expression)] ``` -------------------------------- ### cssselect.Selector Source: https://cssselect.readthedocs.io/ Represents a parsed CSS selector. Users are responsible for handling pseudo-elements. ```APIDOC ## cssselect.Selector ### Description Represents a parsed CSS selector. The `selector_to_xpath()` method can accept this object. Users are responsible for accounting for and rejecting selectors with unknown or unsupported pseudo-elements, as the `pseudo_element` attribute is exposed. ### Methods * **canonical() -> str**: Returns a CSS representation of this selector as a string. * **specificity() -> tuple[int, int, int]**: Returns the specificity of this selector as a tuple of 3 integers. ``` -------------------------------- ### cssselect.FunctionalPseudoElement Source: https://cssselect.readthedocs.io/ Represents a pseudo-element with arguments, like selector::name(arguments). ```APIDOC ## cssselect.FunctionalPseudoElement ### Description Represents a pseudo-element in the format `selector::name(arguments)`. The `name` attribute holds the pseudo-element's identifier, and `arguments` holds its arguments as a list of tokens. ### Attributes * **name** (str): The name (identifier) of the pseudo-element. * **arguments** (Sequence[Token]): The arguments of the pseudo-element as a list of tokens. Note: Tokens are not part of the public API and may change between cssselect versions. ``` -------------------------------- ### Translate CSS Selectors to XPath (HTML) Source: https://cssselect.readthedocs.io/ Use `cssselect.HTMLTranslator()` for translating CSS selectors to XPath, optimized for HTML documents. It handles HTML-specific pseudo-classes and case-insensitivity by default. ```python from cssselect import HTMLTranslator translator = HTMLTranslator() xpath_expr = translator.css_to_xpath('div.myclass > span') # xpath_expr will be 'descendant-or-self::div[@class="myclass"]/descendant-or-self::span' ``` -------------------------------- ### cssselect.GenericTranslator.css_to_xpath Source: https://cssselect.readthedocs.io/ Translates a CSS group of selectors into an XPath 1.0 expression using generic XML rules. Pseudo-elements are not supported. ```APIDOC ## cssselect.GenericTranslator.css_to_xpath ### Description Translates a CSS group of selectors to an XPath expression. This method is suitable for generic XML documents where no specific HTML structure is assumed. Pseudo-elements are not translated as XPath does not directly support them. ### Parameters * **css** (str) - A group of selectors as a string. * **prefix** (str, optional) - This string is prepended to the XPath expression for each selector. Defaults to 'descendant-or-self::'. ### Returns str - The equivalent XPath 1.0 expression as a string. ### Raises * `SelectorSyntaxError` - Raised on invalid selectors. * `ExpressionError` - Raised on unknown or unsupported selectors, including pseudo-elements. ``` -------------------------------- ### cssselect.HTMLTranslator Source: https://cssselect.readthedocs.io/ Translator for (X)HTML documents, with improved handling of HTML-specific pseudo-classes. It offers the same API as GenericTranslator. ```APIDOC ## cssselect.HTMLTranslator ### Description Provides a translator for (X)HTML documents, implementing HTML-specific pseudo-classes according to the HTML5 specification. It assumes no-quirks mode and offers an API identical to `GenericTranslator`. ### Parameters * **xhtml** (bool, optional) - If `False` (default), element and attribute names are case-insensitive. If `True`, they are case-sensitive. ``` -------------------------------- ### Handling Unsupported Selectors/Pseudo-classes Source: https://cssselect.readthedocs.io/ Catch `ExpressionError` when encountering unknown or unsupported selectors or pseudo-classes during XPath translation. This exception is also a subclass of `SelectorError`. ```python from cssselect import GenericTranslator, ExpressionError try: # Assuming ':unknown-pseudo' is not supported GenericTranslator().css_to_xpath('div:unknown-pseudo') except ExpressionError as e: print(f"Expression error: {e}") ``` -------------------------------- ### Translate CSS Selectors to XPath (Generic) Source: https://cssselect.readthedocs.io/ Use `cssselect.GenericTranslator().css_to_xpath()` to translate a CSS selector string directly into an XPath 1.0 expression. This method is suitable for generic XML documents and does not support pseudo-elements by default. ```python from cssselect import GenericTranslator translator = GenericTranslator() xpath_expr = translator.css_to_xpath('div.myclass > span') # xpath_expr will be 'descendant-or-self::div[@class="myclass"]/descendant-or-self::span' ``` -------------------------------- ### Parse CSS Selectors to Selector Objects Source: https://cssselect.readthedocs.io/ Use `cssselect.parse()` to convert a CSS selector string into a list of `Selector` objects. This is useful when you need to work with the parsed structure or handle pseudo-elements explicitly. ```python from cssselect import parse selectors = parse('div, h1.title + p') # selectors is a list of Selector objects ``` -------------------------------- ### Catching All cssselect Exceptions Source: https://cssselect.readthedocs.io/ Use `SelectorError` as a base exception to catch both `SelectorSyntaxError` and `ExpressionError` from `cssselect` operations. ```python from cssselect import parse, SelectorError try: parse('div[invalid-selector') except SelectorError as e: print(f"A cssselect error occurred: {e}") try: GenericTranslator().css_to_xpath('div:unknown-pseudo') except SelectorError as e: print(f"A cssselect error occurred: {e}") ``` -------------------------------- ### Translate Parsed Selector to XPath (Generic) Source: https://cssselect.readthedocs.io/ Use `cssselect.GenericTranslator().selector_to_xpath()` to translate a pre-parsed `Selector` object into an XPath 1.0 expression. This offers more control, especially when deciding how to handle pseudo-elements. ```python from cssselect import parse, GenericTranslator selector = parse('div.myclass > span')[0] translator = GenericTranslator() xpath_expr = translator.selector_to_xpath(selector) # xpath_expr will be 'descendant-or-self::div[@class="myclass"]/descendant-or-self::span' ``` -------------------------------- ### cssselect.parse Source: https://cssselect.readthedocs.io/ Parses a CSS group of selectors into a list of Selector objects. It raises SelectorSyntaxError for invalid selectors. ```APIDOC ## cssselect.parse ### Description Parses a CSS group of selectors into a list of `Selector` objects. This function is useful when you need to work with the parsed structure of CSS selectors. ### Parameters * **css** (str) - A group of selectors as a string. ### Returns list[Selector] - A list of parsed `Selector` objects, one for each selector in the comma-separated group. ### Raises * `SelectorSyntaxError` - Raised on invalid selectors. ``` -------------------------------- ### cssselect.GenericTranslator.selector_to_xpath Source: https://cssselect.readthedocs.io/ Translates a parsed Selector object into an XPath 1.0 expression. Allows for optional translation of pseudo-elements. ```APIDOC ## cssselect.GenericTranslator.selector_to_xpath ### Description Translates a parsed `Selector` object into an XPath 1.0 expression. This method provides fine-grained control over how pseudo-elements are handled during translation. ### Parameters * **selector** (Selector) - A parsed `Selector` object. * **prefix** (str, optional) - This string is prepended to the resulting XPath expression. Defaults to 'descendant-or-self::'. * **translate_pseudo_elements** (bool, optional) - Unless set to `True`, the `pseudo_element` attribute of the selector is ignored. Defaults to `False`. ### Returns str - The equivalent XPath 1.0 expression as a string. ### Raises * `ExpressionError` - Raised on unknown or unsupported selectors. ``` -------------------------------- ### Translate Parsed Selector to XPath (HTML) Source: https://cssselect.readthedocs.io/ Use `cssselect.HTMLTranslator().selector_to_xpath()` to translate a parsed `Selector` object into an XPath expression, tailored for HTML. This method respects HTML-specific conventions. ```python from cssselect import parse, HTMLTranslator selector = parse('div.myclass > span')[0] translator = HTMLTranslator() xpath_expr = translator.selector_to_xpath(selector) # xpath_expr will be 'descendant-or-self::div[@class="myclass"]/descendant-or-self::span' ``` -------------------------------- ### Translate CSS Selector to XPath Source: https://cssselect.readthedocs.io/ Use `GenericTranslator` to convert a CSS selector into an XPath expression. This is useful for parsing CSS selectors for use with XPath engines like lxml. Handle `SelectorError` for invalid selectors. ```python from cssselect import GenericTranslator, SelectorError try: expression = GenericTranslator().css_to_xpath('div.content') except SelectorError: print('Invalid selector.') ``` -------------------------------- ### Handling Pseudo-elements in XPath Translation Source: https://cssselect.readthedocs.io/ When translating parsed selectors to XPath, pseudo-elements are ignored by default. Set `translate_pseudo_elements=True` to attempt translation, though this is primarily handled by `css_to_xpath()`. ```python from cssselect import parse, GenericTranslator selector = parse('a::before')[0] # Selector with a pseudo-element translator = GenericTranslator() # By default, pseudo_element is ignored: xpath_default = translator.selector_to_xpath(selector) # To translate pseudo-elements (if supported by translator): xpath_with_pseudo = translator.selector_to_xpath(selector, translate_pseudo_elements=True) ``` -------------------------------- ### Handling CSS Select Syntax Errors Source: https://cssselect.readthedocs.io/ Catch `SelectorSyntaxError` when parsing invalid CSS selector strings. This exception is a subclass of `SelectorError`. ```python from cssselect import parse, SelectorSyntaxError try: parse('div[invalid-selector') except SelectorSyntaxError as e: print(f"Syntax error: {e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.