cssutils
cssutils is a Python package that provides a set of utility functions for working with CSS (Cascading Style Sheets) stylesheets. The package can be used to parse, modify, and serialize CSS stylesheets, as well as to perform various other operations on the stylesheet such as validation and error handling.
The package provides a high-level API for working with CSS stylesheets, as well as a lower-level API for more advanced use cases.
The high-level API allows developers to easily access and manipulate the styles and rules within a stylesheet, while the lower-level API provides access to the underlying CSS syntax and allows for more fine-grained control over the stylesheet.
cssutils also supports several advanced features such as CSS3 parsing and serialization, handling of @import and @charset rules, and support for various CSS profile such as CSS2, CSS2.1 and CSS3.
Overall, cssutils is a powerful tool for working with CSS stylesheets and is particularly useful for developers working on web development projects who need to manipulate CSS stylesheets programmatically.
Example Use
import cssutils
css = '''/* a comment with umlaut ä */
@namespace html "http://www.w3.org/1999/xhtml";
@variables { BG: #fff }
html|a { color:red; background: var(BG) }'''
sheet = cssutils.parseString(css)
for rule in sheet:
if rule.type == rule.STYLE_RULE:
# find property
for property in rule.style:
if property.name == 'color':
property.value = 'green'
property.priority = 'IMPORTANT'
break
# or simply:
rule.style['margin'] = '01.0eM' # or: ('1em', 'important')
sheet.encoding = 'ascii'
sheet.namespaces['xhtml'] = 'http://www.w3.org/1999/xhtml'
sheet.namespaces['atom'] = 'http://www.w3.org/2005/Atom'
sheet.add('atom|title {color: #000000 !important}')
sheet.add('@import "sheets/import.css";')
# cssutils.ser.prefs.resolveVariables == True since 0.9.7b2
print(sheet.cssText)
@charset "ascii";
@import "sheets/import.css";
/* a comment with umlaut \E4 */
@namespace xhtml "http://www.w3.org/1999/xhtml";
@namespace atom "http://www.w3.org/2005/Atom";
xhtml|a {
color: green !important;
background: #fff;
margin: 1em
}
atom|title {
color: #000 !important
}