Package cssutils :: Module parse'
[hide private]
[frames] | no frames]

Source Code for Module cssutils.parse'

 1  #!/usr/bin/env python 
 2  """a validating CSSParser 
 3   
 4  Usage:: 
 5   
 6      parser = CSSParser() 
 7      stylesheet = p.parse('test1.css', 'ascii') 
 8   
 9      print stylesheet.cssText 
10   
11  """ 
12  __all__ = ['CSSParser'] 
13  __docformat__ = 'restructuredtext' 
14  __author__ = '$LastChangedBy: doerwalter $' 
15  __date__ = '$LastChangedDate: 2007-08-02 22:58:23 +0200 (Do, 02 Aug 2007) $' 
16  __version__ = '0.9.2a2 $LastChangedRevision: 160 $' 
17   
18  import codecs 
19   
20  import cssutils 
21   
22   
23 -class CSSParser(object):
24 """ 25 parses a CSS StyleSheet string or file and 26 returns a DOM Level 2 CSS StyleSheet object 27 """ 28
29 - def __init__(self, log=None, loglevel=None, raiseExceptions=False):
30 """ 31 log 32 logging object 33 loglevel 34 logging loglevel 35 raiseExceptions 36 if log should log (default) or raise 37 """ 38 if log is not None: 39 cssutils.log.setlog(log) 40 if loglevel is not None: 41 cssutils.log.setloglevel(loglevel) 42 43 cssutils.log.raiseExceptions = raiseExceptions
44 45
46 - def parseString(self, cssText):
47 """ 48 parse a CSSStyleSheet string 49 returns the parsed CSS as a CSSStyleSheet object 50 51 cssText 52 CSS string to parse 53 """ 54 stylesheet = cssutils.css.CSSStyleSheet() 55 stylesheet.cssText = cssText 56 return stylesheet
57 58
59 - def parse(self, filename, encoding=None):
60 """ 61 parse a CSSStyleSheet file 62 returns the parsed CSS as a CSSStyleSheet object 63 64 filename 65 name of the CSS file to parse 66 encoding 67 of the CSS file 68 69 TODO: 70 - parse encoding from CSS file? (@charset if given) 71 72 When a style sheet resides in a separate file, user agents must 73 observe the following priorities when determining a style sheet's 74 character encoding (from highest priority to lowest): 75 76 1. An HTTP "charset" parameter in a "Content-Type" field 77 (or similar parameters in other protocols) 78 2. BOM and/or @charset (see below) 79 3. <link charset=""> or other metadata from the linking mechanism 80 (if any) 81 4. charset of referring style sheet or document (if any) 82 5. Assume UTF-8 83 """ 84 if not encoding: 85 encoding = 'utf-8' 86 cssText = codecs.open(filename, 'r', encoding).read() 87 88 # utf-8 BOM 89 if cssText.startswith(u'\ufeff'): 90 cssText = cssText[1:] 91 92 return self.parseString(cssText)
93