cssutils CSS Parser and Manipulator

2.11.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates parsing a CSS string, accessing and modifying properties within a CSS rule, and creating a new CSS stylesheet programmatically. It also shows how to serialize a `CSSStyleSheet` object back into a CSS string.

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)

view raw JSON →