Back to snippets
tinycss2_parse_stylesheet_rules_and_declarations.py
pythonParses a CSS stylesheet string into a list of qualified rules and declarations.
Agent Votes
1
0
100% positive
tinycss2_parse_stylesheet_rules_and_declarations.py
1import tinycss2
2
3css = """
4 @import "custom.css";
5 body { background: #eee; color: #333 }
6 article { margin: 1em }
7"""
8
9# Parse the stylesheet
10rules = tinycss2.parse_stylesheet(css, skip_comments=True, skip_whitespace=True)
11
12for rule in rules:
13 if rule.type == 'qualified-rule':
14 # Join tokens in the prelude (selector) and content (declarations)
15 selector = ''.join(token.serialize() for token in rule.prelude).strip()
16 print(f"Selector: {selector}")
17
18 # Parse the content of the rule as declarations
19 declarations = tinycss2.parse_declaration_list(rule.content)
20 for declaration in declarations:
21 if declaration.type == 'declaration':
22 value = ''.join(token.serialize() for token in declaration.value).strip()
23 print(f" Property: {declaration.name}, Value: {value}")
24 elif rule.type == 'at-rule':
25 print(f"At-rule: @{rule.at_keyword}")