cssutils CSS Parser and Manipulator
cssutils is a Python library for parsing and manipulating CSS (Cascading Style Sheets). It provides a full DOM interface for CSS stylesheets, rules, and declarations, allowing for programmatic creation, modification, and serialization of CSS. The library is currently at version 2.11.1 and sees regular maintenance releases, typically every few months.
Warnings
- breaking Major API overhaul in version 2.0.0. All custom API previously found in `cssutils.css` (e.g., `cssutils.css.CSSStyleSheet`, `cssutils.css.Rule`) and other custom classes were removed. All functionality is now exclusively available through the W3C DOM interface.
- gotcha Default serialization (`cssText`) might not produce the exact output format expected (e.g., indentation, line breaks, specific property ordering).
- gotcha cssutils uses Python's `logging` module for warnings and errors during parsing. By default, only `WARNING` and above messages might be shown, potentially masking minor parsing issues.
Install
-
pip install cssutils
Imports
- cssutils
import cssutils
- CSSStyleSheet
import cssutils sheet = cssutils.CSSStyleSheet()
Quickstart
import cssutils
import logging
# Suppress cssutils logging for cleaner output in example
cssutils.log.setLevel(logging.CRITICAL)
# Parse a CSS string
sheet = cssutils.parseString('a { color: red; font-size: 16px; }')
# Accessing rules and properties
rule = sheet.cssRules[0] # Get the first rule
print(f"Selector: {rule.selectorText}") # Output: Selector: a
print(f"Color: {rule.style.color}") # Output: Color: red
print(f"Font Size: {rule.style.fontSize}") # Output: Font Size: 16px
# Modifying a rule
rule.style.color = 'blue'
# Creating a new stylesheet and adding a rule
new_sheet = cssutils.CSSStyleSheet()
new_sheet.add('p { margin: 10px; }')
# Add the modified rule from the first sheet to the new one
new_sheet.add(rule)
# Serialize the new stylesheet to a string
print('\n--- New Stylesheet ---')
print(new_sheet.cssText)