Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
106 lines (73 sloc) 2.96 KB

CSS 3 Modules

Selectors 3

On :attr:`RuleSet.selector`, the :meth:`~.token_data.TokenList.as_css` method can be used to serialize a selector back to an Unicode string.

>>> import tinycss
>>> stylesheet = tinycss.make_parser().parse_stylesheet(
...     'div.error, #root > section:first-letter { color: red }')
>>> selector_string = stylesheet.rules[0].selector.as_css()
>>> selector_string
u'div.error, #root > section:first-letter'

This string can be parsed by cssselect. The parsed objects have information about pseudo-elements and selector specificity.

>>> import cssselect
>>> selectors = cssselect.parse(selector_string)
>>> [s.specificity() for s in selectors]
[(0, 1, 1), (1, 0, 2)]
>>> [s.pseudo_element for s in selectors]
[None, u'first-letter']

These objects can in turn be translated to XPath expressions. Note that the translation ignores pseudo-elements, you have to account for them somehow or reject selectors with pseudo-elements.

>>> xpath = cssselect.HTMLTranslator().selector_to_xpath(selectors[1])
>>> xpath
u"descendant-or-self::*[@id = 'root']/section"

Finally, the XPath expressions can be used with lxml to find the matching elements.

>>> from lxml import etree
>>> compiled_selector = etree.XPath(xpath)
>>> document = etree.fromstring('''<section id="root">
...   <section id="head">Title</section>
...   <section id="content">
...     Lorem <section id="sub-section">ipsum</section>
...   </section>
... </section>''')
>>> [el.get('id') for el in compiled_selector(document)]
['head', 'content']

Find more details in the cssselect documentation.

Color 3

This module implements parsing for the <color> values, as defined in CSS 3 Color.

The (deprecated) CSS2 system colors are not supported, but you can easily test for them if you want as they are simple IDENT tokens. For example:

if token.type == 'IDENT' and token.value == 'ButtonText':
    return ...

All other values types are supported:

  • Basic, extended (X11) and transparent color keywords;
  • 3-digit and 6-digit hexadecimal notations;
  • rgb(), rgba(), hsl() and hsla() functional notations.
  • currentColor

This module does not integrate with a parser class. Instead, it provides a function that can parse tokens as found in :attr:`.css21.Declaration.value`, for example.

Paged Media 3

Other CSS modules

To add support for new CSS syntax, see :ref:`extending`.

Something went wrong with that request. Please try again.