Options to parse a given stylesheet: Get an instance of cssutils.CSSParser and use the provided parse* methods or for simpler parsing use the parse* convienience functions.
The parser is reusable.
Parse a CSS StyleSheet from URL, string or file and return a DOM Level 2 CSS StyleSheet object.
Usage:
parser = CSSParser()
# optionally
parser.setFetcher(fetcher)
sheet = parser.parseFile('test1.css', 'ascii')
print sheet.cssText
Retrieve content from filename and parse it. Errors may be raised (e.g. IOError).
Parameters: |
|
---|---|
Returns: |
Parse cssText as CSSStyleSheet. Errors may be raised (e.g. UnicodeDecodeError).
Parameters: |
|
---|---|
Returns: |
Retrieve content from URL href and parse it. Errors may be raised (e.g. URLError).
Parameters: |
|
---|---|
Returns: |
Replace the default URL fetch function with a custom one.
Parameter: | fetcher – A function which gets a single parameter
and must return (encoding, content) where encoding is the HTTP charset normally given via the Content-Type header (which may simply omit the charset in which case encoding would be None) and content being the string (or unicode) content. The Mimetype should be ‘text/css’ but this has to be checked by the fetcher itself (the default fetcher emits a warning if encountering a different mimetype). Calling setFetcher with fetcher=None resets cssutils to use its default function. |
---|
If you want to control how imported stylesheets are read you may define a custom URL fetcher (e.g. would be needed on Google AppEngine as urllib2, which is normally used, is not available. A GAE specific fetcher is included in cssutils from 0.9.5a1 though.)
A custom URL fetcher may be used during parsing via CSSParser.setFetcher(fetcher) (or as an init parameter). The so customized parser is reusable. The fetcher is called when an @import rule is found and the referenced stylesheet is about to be retrieved.
Example:
def fetcher(url):
return 'ascii', '/*test*/'
parser = cssutils.CSSParser(fetcher=fetcher)
parser.parse...
Example 2 with a fetcher returning a unicode string:
def fetcher(url):
return None, u'/*test*/'
parser = cssutils.CSSParser(fetcher=fetcher)
parser.parse...
To omit parsing of imported sheets just define a fetcher like lambda url: None (A single None is sufficient but returning None, None would be clearer).
You may also define a fetcher which overrides the internal encoding for imported sheets with a fetcher that returns a (normally HTTP) encoding depending e.g on the URL.
Shortcuts for initializing a new cssutils.CSSParser and use its parse* methods. Parsing a stylesheet this way does not raise any exceptions if an error occurs but parses CSS as defined in the specifications. If you need advanced parser handline use cssutils.CSSParser directly.