Registry / serialization / cssutils

cssutils

JSON →
library2.15.0pypypi✓ verified 30d ago

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.

pip install cssutils
INSTALL
IMPORT
SIG · CSSUTILS
C
cssutils
serializationpythonv2.15.0
Install
1.9s avg
Import
310ms
Disk
20MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v2.15.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.316s · 21.2MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 1.9s · import 0.304s · 24MB
20MB installed
● package 20MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

cssutils
✓ import cssutils
CSSStyleSheet
✓ import cssutils sheet = cssutils.CSSStyleSheet()
✗ from cssutils.css import CSSStyleSheet
The 'cssutils.css' module and custom classes were removed in version 2.x. All functionality is now accessed through the main `cssutils` module via the W3C DOM API.

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)
Debug
Known issues
breakingMajor 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.
fix
Rewrite code to use the main `cssutils` module and its W3C DOM-compliant methods and objects (e.g., `cssutils.parseString()`, `cssutils.CSSStyleSheet()`). Do not use `from cssutils.css import ...`.
affects: 2.0.0 and later
gotchaDefault serialization (`cssText`) might not produce the exact output format expected (e.g., indentation, line breaks, specific property ordering).
fix
Customize serialization preferences using `cssutils.ser.prefs`. For example, `cssutils.ser.prefs.indent = 4` to set indentation or `cssutils.ser.prefs.keepemptyrules = False` to remove empty rules.
affects: All 2.x versions
gotchacssutils 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.
fix
Configure the `cssutils.log` level to `INFO` or `DEBUG` to see more detailed parsing messages, especially during development or debugging problematic CSS. Example: `cssutils.log.setLevel(logging.INFO)`.
affects: All 2.x versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'cssutils'
The cssutils library is not installed in the current Python environment.
fix
Install the cssutils library using pip: `pip install cssutils`
AttributeError: module 'cssutils' has no attribute 'getUrls' OR AttributeError: 'str' object has no attribute 'type' (when using cssutils.getUrls)
The `cssutils.getUrls` function expects a parsed `CSSStyleSheet` object as input, not a raw CSS string or is incorrectly called directly on the module.
fix
First parse the CSS string into a `CSSStyleSheet` object using `cssutils.parseString()`, then pass the resulting sheet object to `cssutils.getUrls()`.
```python
import cssutils
css_string = "@import url('path/to/style.css'); a { color: blue; }"
sheet = cssutils.parseString(css_string)
for url in cssutils.getUrls(sheet):
    print(url)
```
WARNING CSSStylesheet: Unknown @rule found. OR ERROR MediaQuery: Unexpected syntax
cssutils issues logging messages (warnings or errors) for non-standard CSS, unknown `@rules` (like vendor prefixes), or syntactical issues it encounters during parsing, even if `validate=False` is set.
fix
To suppress these logging messages, configure Python's logging system to a higher level (e.g., ERROR or CRITICAL) for the `cssutils` logger.
```python
import logging
import cssutils

cssutils.log.setLevel(logging.ERROR) # Suppress warnings and info messages
# Or to completely disable cssutils logging for a parser instance:
# parser = cssutils.CSSParser(log=logging.getLogger('null'))

css_text = "@-webkit-keyframes anim { from { opacity: 0; } to { opacity: 1; } } div { -moz-border-radius: 5px; }"
sheet = cssutils.parseString(css_text)
# Your cssutils logic here will now run without these warnings
```
SyntaxError: invalid syntax (often pointing to 'except xml.dom.HierarchyRequestErr, e:')
An older version of cssutils, which uses Python 2 exception handling syntax (`except Exception, e:`), is being run in a Python 3 environment that requires `except Exception as e:`.
fix
Update cssutils to a version compatible with your Python 3 interpreter. This typically involves upgrading the package: `pip install --upgrade cssutils`.
Upgrade
Version history
2.15.0latest on PyPI · released Apr 27, 2026
Audit
Dependencies

No dependency data recorded yet.

Agent activity
10 hits · last 30 days
node
8
Amazon
1
Resources
cssutils — pip install cssutils · libregistry