1
2 """a validating CSSParser
3 """
4 __all__ = ['CSSParser']
5 __docformat__ = 'restructuredtext'
6 __version__ = '$Id: parse.py 1151 2008-03-18 22:35:53Z cthedot $'
7
8 import codecs
9 import cssutils
10
12 """
13 parses a CSS StyleSheet string or file and
14 returns a DOM Level 2 CSS StyleSheet object
15
16 Usage::
17
18 parser = CSSParser()
19 sheet = p.parse('test1.css', 'ascii')
20
21 print sheet.cssText
22 """
23 - def __init__(self, log=None, loglevel=None, raiseExceptions=False):
39
40 - def parseString(self, cssText, encoding=None, href=None, media=None,
41 title=None):
42 """Return parsed CSSStyleSheet from given string cssText.
43
44 cssText
45 CSS string to parse
46 encoding
47 encoding of the CSS string. if ``None`` the encoding will be read
48 from a @charset rule. If there is none, the parser will fall back
49 to UTF-8. If cssText is a unicode string encoding will be ignored.
50 href
51 The href attribute to assign to the parsed style sheet.
52 Used to resolve other urls in the parsed sheet like @import hrefs
53 media
54 The media attribute to assign to the parsed style sheet
55 (may be a MediaList, list or a string)
56 title
57 The title attribute to assign to the parsed style sheet
58 """
59 if isinstance(cssText, str):
60
61 cssText = codecs.getdecoder('css')(cssText, encoding=encoding)[0]
62 sheet = cssutils.css.CSSStyleSheet()
63
64 sheet._href = href
65 sheet.media = cssutils.stylesheets.MediaList(media)
66 sheet.title = title
67 sheet.cssText = self.__tokenizer.tokenize(cssText, fullsheet=True)
68 return sheet
69
70 - def parse(self, filename, encoding=None, href=None, media=None, title=None):
71 """Retrieve and return a CSSStyleSheet from given filename.
72
73 filename
74 of the CSS file to parse
75 encoding
76 of the CSS file, ``None`` defaults to encoding detection from
77 a @charset rule
78
79 for other parameters see ``parseString``
80 """
81 return self.parseString(open(filename, 'rb').read(), encoding=encoding,
82 href=href, media=media, title=title)
83
84 - def parseURL(self, url, encoding=None, href=None, media=None, title=None):
85 """Retrieve and return a CSSStyleSheet from given url.
86
87 url
88 url of the CSS file to parse
89 encoding
90 if given overrides detected HTTP encoding
91
92 for other parameters see ``parseString``
93 """
94 return self.parseString(cssutils.util._readURL(url, encoding),
95 href=href, media=media,
96 title=title)
97