def test_css(self): file = os.path.join(settings.STATIC_ROOT, 'css\\test.css') kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'} # Перевірка отримання селектору sel = cssmanager.get_selectors(file) self.assertEqual(sel, ['body']) # Зміна властивостей селектора та збереження в файл dic = {u'color': u'#333333', u'width': u'1903px', u'background-color': u'#ffffff', u'height': u'1682px'} cssmanager.set_selectors(file, 'body', dic) #sel=cssmanager.get_selectors(file) css = cssutils.parseFile(file) param = css.cssRules.item(0).style.getPropertyValue('width') self.assertEqual(param, '1903px') dic = {u'color': u'#333333', u'width': u'1203px', u'background-color': u'#ffffff', u'height': u'1682px'} cssmanager.set_selectors(file, 'body', dic) css = cssutils.parseFile(file) param = css.cssRules.item(0).style.getPropertyValue('width') self.assertEqual(param, '1203px')
def copy_css(self): base_dir = os.path.abspath(os.path.dirname(self.css_file)) self.font_list = [] def replace_url(url): source_file = os.path.abspath(os.path.join(base_dir, url)) if os.path.splitext(url)[1].lower() in ('.ttf', '.otf'): dest_file = os.path.abspath(os.path.join(self.temp_content_dir, 'fonts', os.path.basename(source_file))) new_url = 'fonts/' + os.path.basename(url) self.font_list.append(new_url) else: dest_file = os.path.abspath( os.path.join(self.temp_content_dir, 'images', 'css_' + os.path.basename(source_file))) new_url = 'images/css_' + os.path.basename(url) try: copy_file(source_file, dest_file) except: self.log.error('File {0}, referred by css, not found.'.format(url)) return new_url if self.parse_css: cssutils.profile.addProfile('CSS extentions', {'-webkit-hyphens': 'none', 'adobe-hyphenate': 'none', '-moz-hyphens': 'none', '-ms-hyphens': 'none', 'hyphens': 'none|manual|auto'}) stylesheet = cssutils.parseFile(self.css_file) cssutils.replaceUrls(stylesheet, replace_url) write_file(str(stylesheet.cssText, 'utf-8'), os.path.join(self.temp_content_dir, 'stylesheet.css')) else: copy_file(self.css_file, os.path.join(self.temp_content_dir, 'stylesheet.css'))
def update_css(opftree, epub_dir, old_name_path, new_name_path): css_items = etree.XPath( '//opf:item[@media-type="text/css"]', namespaces=OPFNS )(opftree) for c in css_items: sheet = cssutils.parseFile(os.path.join(epub_dir, c.get('href')), validate=True) old_css_path = os.path.relpath(old_name_path, os.path.dirname(c.get('href'))) new_css_path = os.path.relpath(new_name_path, os.path.dirname(c.get('href'))) for rule in sheet: if rule.type == rule.FONT_FACE_RULE: for p in rule.style: if p.name == 'src': values = cssutils.css.PropertyValue(p.value) for av in values: if ( av.type == 'URI' and av.uri == old_css_path ): p.value = 'url(%s)' % new_css_path with open(os.path.join(epub_dir, c.get('href')), 'w') as f: f.write(sheet.cssText)
def run(): selectors = [] styles_dir = os.path.join(os.path.dirname(__file__), "../media/styles/") for filename in os.listdir(styles_dir): if not filename.endswith(".css"): continue if filename.startswith("ie"): continue print >> sys.stderr, "Processing", filename filename = os.path.join(styles_dir, filename) sheet = cssutils.parseFile(filename) for rule in sheet: if not isinstance(rule, cssutils.css.CSSStyleRule): continue if rule.style.getPropertyValue("display") == "inline-block": selectors.append(rule.selectorText) selectors.sort() print """%s { display: inline; zoom: 1; }""" % ",\n".join(selectors)
def _loadCSSTemplate(self, css_template_file, group_name, url_prefix_substitutions=None): """See `__init__`.""" smartsprites_exp = re.compile( r'/\*+([^*]*sprite-ref: [^*]*)\*/') self.css_object = cssutils.parseFile(css_template_file) self.sprite_info = [] for rule in self.css_object: if rule.cssText is None: continue match = smartsprites_exp.search(rule.cssText) if match is not None: parameters = self._parseCommentParameters(match.group(1)) # Currently, only a single combined image is supported. if parameters['sprite-ref'] == group_name: filename = self._getSpriteImagePath( rule, url_prefix_substitutions) if filename == '': raise AssertionError( "Missing background-image url for %s css style" % rule.selectorText) self.sprite_info.append( dict(filename=filename, rule=rule)) if len(self.sprite_info) == 0: raise AssertionError( "No sprite-ref comments for group %r found" % group_name)
def process(self, files): for f in files: if not f['resource_path'].endswith('.css') or f['type'] != 'file': yield f continue self._counter += 1 fs_rpath = f['filesystem_path'] sheet = cssutils.parseFile(fs_rpath) sheet.setSerializer(self.serializer) for url in cssutils.getUrls(sheet): u = urlparse(url) if u.scheme or u.netloc or not u.path.startswith('./'): logging.warning('non-relative URL used in CSS: %s' % url) if self.resolve_imports: sheet = cssutils.resolveImports(sheet) target = os.path.join( self._tmpdir, str(self._counter) + '-' + os.path.basename(fs_rpath)) out_f = open(target, 'wb') try: out_f.write(sheet.cssText) finally: out_f.close() f['filesystem_path'] = target yield f
def sprite(directory, cssfile, outfile=None, offset=SPRITE_OFFSET): logger = logging.getLogger('cssutils') logger.setLevel(logging.FATAL) cssutils.log.setLog(logger) if outfile is None: outfile = cssfile style_sheet = cssutils.parseFile(cssfile, validate=False) # Calculate relative directory name from CSS file to the output directory reldir = os.path.relpath(directory, os.path.dirname(cssfile)) reldir = reldir.replace('\\', '/').rstrip('/') if reldir == '.': reldir = '' # Name the default sprite the same as the CSS file default_sprite_name, _ = os.path.splitext(os.path.basename(cssfile)) sprites = get_sprites(style_sheet.cssRules, default_sprite_name) for sprite in sprites: sprite.generate(directory, reldir, offset=offset) with open(outfile, 'wb') as f: f.write(fixup_css(style_sheet.cssText)) return True
def handle(self, *args, **options): template_dirs = list(settings.TEMPLATE_DIRS) template_dirs += app_template_dirs pkg_name = 'templates/' for app in settings.INSTALLED_APPS: try: path = resource_filename(app, pkg_name).decode(settings.FILE_CHARSET) if os.path.exists(path): template_dirs.append(path) except: pass for static_css in args: absolute_path = finders.find(static_css) sheet = cssutils.parseFile(absolute_path) for rule in sheet.cssRules: if hasattr(rule, "selectorList"): for selector in rule.selectorList: for seq in selector.seq: if seq.type == "class": # grep for that class cls = seq.value.replace(".", "") res = "" for folder in template_dirs: stdout, stderr = grep(folder, cls) res += stdout if res == "": print ".%s\n\t(...%s:%i)" % (cls, sheet.href[-16:], seq.line)
def testLoadStyles(self): styleSheet = cssutils.parseFile('../styles.css') rules = styleSheet.cssRules self.assertEqual(25, rules.length) rule = self.simpleLookup(styleSheet, "h2") self.assertIsNotNone(rule) rule = self.simpleLookup(styleSheet, "h5") self.assertIsNone(rule) rule = self.simpleLookup(styleSheet, 'code[lang="java"]') self.assertIsNotNone(rule) prop = rule.style.getProperty('background-color') self.assertEqual(prop.name, 'background-color') self.assertEqual(prop.propertyValue.length, 1) # expect one property value value = prop.propertyValue.item(0) self.assertEquals(value.type, cssutils.css.Value.COLOR_VALUE) colorValue = 'rgb({},{},{})'.format(value.red, value.green, value.blue) self.assertEquals(colorValue, 'rgb(0,0,255)') #======================================================================= # rule = self.simpleLookup(styleSheet, 'code[lang="xml"]') # prop = rule.style.getProperty('background-color') # value = prop.propertyValue.item(0) # colorValue = 'rgb({},{},{})'.format(value.red, value.green, value.blue) #======================================================================= # test unknown property prop = rule.style.getProperty('foreground-color') self.assertIsNone(prop)
def minify_sources(sources, ext, fs_root=''): import cssutils if 'js' in ext: js_minify = JavascriptMinify() minified_sources = [] for source in sources: # generate full path to source no_ext_source = os.path.splitext(source)[0] full_source = os.path.join(fs_root, (no_ext_source + ext).lstrip('/')) # generate minified source path full_source = os.path.join(fs_root, (source).lstrip('/')) no_ext_full_source = os.path.splitext(full_source)[0] minified = no_ext_full_source + ext f_minified_source = open(minified, 'w') # minify js source (read stream is auto-closed inside) if 'js' in ext: js_minify.minify(open(full_source, 'r'), f_minified_source) # minify css source if 'css' in ext: serializer = get_serializer() sheet = cssutils.parseFile(full_source) sheet.setSerializer(serializer) cssutils.ser.prefs.useMinified() f_minified_source.write(sheet.cssText) f_minified_source.close() minified_sources.append(no_ext_source + ext) return minified_sources
def process_file(source): sheet = cssutils.resolveImports(cssutils.parseFile(source)).cssText hash = hashlib.md5() hash.update(sheet) filename = OUT_PREFIX + hash.hexdigest() + FILENAME_POSTFIX with open(filename, "w") as out: out.write(sheet) return source, filename
def loadFromFile(self, skin): """ Carica il CSS da un file. Il CSS viene aperto e serializzato da cssutils e ne viene effettuato il parsing da SkinParser """ self.cssFile = skin skin = cssutils.parseFile(skin).cssText self.__parse(skin)
def validate_css(filepath, filetype): """Validate if the contents of file is a valid css file """ if filetype in CSS_CONTENT_TYPE: sheet = cssutils.parseFile(filepath) if sheet.cssText.strip(): return True return False
def clean_css(self, cssfile): try: content = cssutils.parseFile(cssfile) if content: writer = open(cssfile, 'w') writer.write(content) writer.close() print "Cleaned", cssfile except Exception, e: print e
def update_css_font_families(epub_dir, opftree): def find_css_font_file_families(epub_dir, opftree): font_families = [] css_items = etree.XPath( '//opf:item[@media-type="text/css"]', namespaces=OPFNS )(opftree) for c in css_items: css_file_path = os.path.join(epub_dir, c.get('href')) sheet = cssutils.parseFile(css_file_path, validate=True) for rule in sheet: if rule.type == rule.FONT_FACE_RULE: css_font_family = None font_file_family = None for p in rule.style: if p.name == 'font-family' and css_font_family is None: try: css_font_family = p.value.split( ',')[0].strip().strip('"').strip("'") except: continue continue if p.name == 'src' and font_file_family is None: ffs = rule.style.getProperty(p.name).propertyValue ff_url = ffs.item(0).value with open(os.path.join( os.path.dirname(css_file_path), ff_url ), 'rb') as f: lfp = list_font_basic_properties(f.read()) lfp = list(lfp) if 'subset of' in lfp[0]: lfp[0] = re.sub( r'\w+?\s-\ssubset\sof\s', '', lfp[0] ) font_file_family = lfp[0] continue font_families.append([css_font_family, font_file_family]) return font_families print('* Updating font-family in all CSS files...') ff_list = find_css_font_file_families(epub_dir, opftree) css_items = etree.XPath('//opf:item[@media-type="text/css"]', namespaces=OPFNS)(opftree) for c in css_items: css_file_path = os.path.join(epub_dir, c.get('href')) sheet = cssutils.parseFile(css_file_path, validate=True) for ff in ff_list: fix_sheet(sheet, ff[0], ff[1], False) with open(os.path.join(epub_dir, c.get('href')), 'w') as f: f.write(sheet.cssText)
def csscombine(path=None, url=None, cssText=None, href=None, sourceencoding=None, targetencoding=None, minify=True, resolveVariables=False): """Combine sheets referred to by @import rules in given CSS proxy sheet into a single new sheet. :returns: combined cssText, normal or minified :Parameters: `path` or `url` or `cssText` + `href` path or URL to a CSSStyleSheet or a cssText of a sheet which imports other sheets which are then combined into one sheet. `cssText` normally needs `href` to be able to resolve relative imports. `sourceencoding` = 'utf-8' explicit encoding of the source proxysheet `targetencoding` encoding of the combined stylesheet `minify` = True defines if the combined sheet should be minified `resolveVariables` = False defined if variables in combined should be resolved """ cssutils.log.info(u'Combining files from %r' % url, neverraise=True) if sourceencoding is not None: cssutils.log.info(u'Using source encoding %r' % sourceencoding, neverraise=True) if path and not cssText: src = cssutils.parseFile(path, encoding=sourceencoding) elif url: src = cssutils.parseUrl(url, encoding=sourceencoding) elif cssText: src = cssutils.parseString(cssText, href=href, encoding=sourceencoding) else: sys.exit('Path or URL must be given') result = cssutils.resolveImports(src) result.encoding = targetencoding cssutils.log.info(u'Using target encoding: %r' % targetencoding, neverraise=True) if minify: # save old setting and use own serializer oldser = cssutils.ser cssutils.setSerializer(cssutils.serialize.CSSSerializer()) cssutils.ser.prefs.useMinified() cssutils.ser.prefs.resolveVariables = resolveVariables cssText = result.cssText cssutils.setSerializer(oldser) else: rv = cssutils.ser.prefs.resolveVariables cssutils.ser.prefs.resolveVariables = resolveVariables cssText = result.cssText cssutils.ser.prefs.resolveVariables = rv return cssText
def assertOutputCss(self, *selector_positions): self.assertTrue(os.path.isfile(self.output_css)) parsed_css = cssutils.parseFile(self.output_css) self.assertEquals(4, len(parsed_css.cssRules)) image_rule = parsed_css.cssRules[0] self.assertEquals('.sprite-output-sprite', image_rule.selectorText) self.assertEquals('url(%s)' % self.output_png, image_rule.style.background) i = 1 for selector, position in selector_positions: rule = parsed_css.cssRules[i] self.assertEquals(selector, rule.selectorText) self.assertEquals(position, rule.style.backgroundPosition) i += 1
def minify_sources(sources, ext, fs_root='', timestamp=False): """Use utilities to minify javascript or css. :param sources: Paths of source files :param ext: Type of files :param fs_root: root of file (normally public dir) :type sources: string :type ext: js or css :type fs_root: string :returns: List of paths to minified sources """ if 'js' in ext: js_minify = JavascriptMinify() minified_sources = [] for source in sources: # generate full path to source no_ext_source = path.splitext(source)[0] full_source = path.join(fs_root, (no_ext_source + ext).lstrip('/')) # generate minified source path full_source = path.join(fs_root, (source).lstrip('/')) no_ext_full_source = path.splitext(full_source)[0] minified = no_ext_full_source + ext f_minified_source = open(minified, 'w') try: # minify js source (read stream is auto-closed inside) if 'js' in ext: js_minify.minify(open(full_source, 'r'), f_minified_source) # minify css source if 'css' in ext: sheet = cssutils.parseFile(full_source) cssutils.setSerializer(CSSUtilsMinificationSerializer()) cssutils.ser.prefs.useMinified() f_minified_source.write(sheet.cssText) finally: f_minified_source.close() if no_ext_source.endswith('COMBINED'): minified_sources.append(no_ext_source + ext) else: minified_sources.append(no_ext_source + generate_timestamp(timestamp) + ext) return minified_sources
def __init__(self, filePath=None, string=None): if filePath: self.css = cssutils.parseFile(filePath) elif string: self.css = cssutils.parseString(string) rules = self.css.cssRules selectors = [] for rule in rules: if not hasattr(rule, "selectorList"): continue for selector in rule.selectorList: selectorText = selector.selectorText selectorComponents = selectorText.split(" ") selectors.extend(selectorComponents) self.selectors = selectors
def format(self): if not os.path.isfile(self._target): raise FileNotFoundError # Disable cssutils warnings cssutils.log.setLevel(logging.CRITICAL) # Setup CSS serializer cssutils.ser.prefs.indent = "\t" if self._useTabs else " " * self._indent cssutils.ser.prefs.keepEmptyRules = True cssutils.ser.prefs.omitLastSemicolon = False cssutils.ser.prefs.indentClosingBrace = False styles = cssutils.parseFile(self._target) cssText = styles.cssText.decode() with open(self._target, "w") as out: out.write(cssText)
def cssm(cssfile="/"): if os.path.exists(__out) is False: os.mkdir(__out) for line in file('stylelist','rU').readlines(): if not line.startswith('#') and line.find(cssfile) > 0: path,name = line.rstrip('\n').rsplit('/',1) out = __out+path.lstrip('./').replace('/','-') if os.path.exists(out) is False: os.mkdir(out) try: cssmerge(line.rstrip('\n'),file(out + '/' + path.lstrip('./').replace('/','-') + '.css', 'w')) css = cssutils.parseFile(out + '/' + path.lstrip('./').replace('/','-') + '.css') cssutils.ser.prefs.useMinified() file(out + '/' + path.lstrip('./').replace('/','-') + '.css', 'w').write(css.cssText) except: print out + '/' + path.lstrip('./').replace('/','-') + '.css'
def main(list_of_files): file_count = len(list_of_files) sheets = [] rules = {} common_rules = [] for file_path in list_of_files: sheets.append(cssutils.parseFile(file_path)) for sheet in sheets: for rule in sheet.cssRules: if rules.get((rule.selectorText, rule.style.cssText)): rules[(rule.selectorText, rule.style.cssText)][1] += 1 if rules[(rule.selectorText, rule.style.cssText)][1] == file_count: common_rules.append(rule.cssText) else: rules[(rule.selectorText, rule.style.cssText)] = [rule, 1] with sys.stdout as out: out.write('\n\n'.join(common_rules))
def main(): def p(s, l=0): c = '#=-'[l] * (30 - l*10) for r in s.cssRules.rulesOfType(cssutils.css.CSSRule.IMPORT_RULE): print c print r.href print c print r.styleSheet.cssText print p(r.styleSheet, l=l+1) print s = cssutils.parseFile(os.path.join('sheets', '1import.css')) print s.cssText print p(s)
def patchstylesheet(filename): #First parse the old stylesheet. stylesheet=cssutils.parseFile(filename) #Process every rule that has a style attached to it. for cssrule in stylesheet.cssRules: if hasattr(cssrule, 'style'): #Make everything OpenDyslexic cssrule.style.fontFamily = "OpenDyslexic" #Add 0.125em to the font size and use 1.125em as default if undefined. if not "em" in cssrule.style.fontSize: cssrule.style.fontSize= "1.125em" else: cssrule.style.fontSize = str(float(re.sub("[^0-9.]", "", cssrule.style.fontSize))+0.125) + "em" #Add 30% to the line height and use 130% as default if undefined. if not "%" in cssrule.style.lineHeight: cssrule.style.lineHeight = "130%" else: cssrule.style.lineHeight = str(int(re.sub("[^0-9]", "", cssrule.style.lineHeight))+30) + "%" #Insert an extra fontface rule for each bold/italic flag combination. insertfontface(stylesheet,1,"""@font-face { font-family: 'OpenDyslexic'; src:url(fonts/OpenDyslexic-Regular.otf); }""") insertfontface(stylesheet,2,"""@font-face { font-family: "OpenDyslexic"; src: url("fonts/OpenDyslexic-Bold.otf"); font-weight: bold; }""") insertfontface(stylesheet,3,"""@font-face { font-family: "OpenDyslexic"; src: url("fonts/OpenDyslexic-Italic.otf"); font-style: italic, oblique; }""") insertfontface(stylesheet,4,"""@font-face { font-family: "OpenDyslexic"; src: url("fonts/OpenDyslexic-BoldItalic.otf"); font-weight: bold; font-style: italic, oblique; }""") #Write back the patched CSS file. output=open(filename,"w") output.write(stylesheet.cssText) output.close() return
def compare(output_file): filenames = getFileNames() output = [] curr = 0 total = len(filenames) for fn in filenames: # print fn path = os.path.join('css', fn) stylesheet = cssutils.parseFile(path, validate=False) readCSS(stylesheet, output) curr += 1 sys.stdout.write("\rcomparing: " + ("%.2f" % (100.0 * curr / total)) + '%') sys.stdout.flush() postProcess(output) # output = pprint(output) with open(output_file, 'wt') as out: pprint(output, stream=out) sys.stdout.write("\nmission completed :)")
def update_css(opftree, epub_dir, old_name_path, new_name_path): css_items = etree.XPath( '//opf:item[@media-type="text/css"]', namespaces=OPFNS )(opftree) for c in css_items: sheet = cssutils.parseFile(os.path.join(epub_dir, c.get('href')), validate=True) old_css_path = os.path.relpath( old_name_path, os.path.dirname(c.get('href')) ).replace('\\', '/') new_css_path = os.path.relpath( new_name_path, os.path.dirname(c.get('href')) ).replace('\\', '/') fix_sheet(sheet, old_css_path, new_css_path, True) with open(os.path.join(epub_dir, c.get('href')), 'w') as f: f.write(sheet.cssText)
def css_file_inject_images(infile,outfile): sourceDir = os.path.dirname( infile ) sourceFile = os.path.basename( infile ) outputFile = os.path.basename(outfile) outputDir = os.path.dirname(os.path.abspath( outfile ) ) if not os.path.isdir(sourceDir): sys.exit('ERROR: Source directory not found %s' % sourceDir ) if not os.path.isfile( os.path.join( sourceDir, sourceFile ) ): sys.exit('ERROR: Source file not found %s' % sourceFile ) if not os.path.isdir(outputDir): sys.exit('ERROR: Output directory not found %s' % outputDir ) stylesheet = parseFile( os.path.join( sourceDir, sourceFile ) ) outputCSS = css_inject_images(stylesheet,sourceDir) out = open( os.path.join( outputDir, outputFile ), "w" ) out.write( outputCSS ) out.close()
def css(filepath): """Convert css files into json representation :filepath: path to file :returns: dict """ sheet = cssutils.parseFile(filepath) converted = [] for rule in sheet: if rule.type == rule.STYLE_RULE: content = rule.style['content'] selectorText = rule.selectorText.lower().strip() matched = re.match(r'\.(?P<name>[a-z0-9\-_]+)\s*:before', selectorText) if content and matched: unicode_as_int = ord(content[1]) name = matched.groupdict()['name'] converted.append({ 'name': name, 'unicode': unicode_as_int }) return converted
def main(): ''' Argument parser init ''' parser = argparse.ArgumentParser(description='Parse CSS files for elements ' 'with a defined z-index and ' 'list them') parser.add_argument('-v', '--version', dest='version', action='store_true', help='show package version information and exit') parser.add_argument('files', nargs='*') args = parser.parse_args() if args.version: print "zlist v%s" % get_version() sys.exit(0) ''' Iterate files supplied as args and parse them ''' for filename in args.files: sheet = cssutils.parseFile(filename) zlist = [] for rule in sheet: if rule.type == rule.STYLE_RULE: z = None for prop in rule.style: if prop.name == 'z-index': z = prop.value if z: zlist.append([z, rule.selectorList]) if zlist: print "%s: %d z-index declaration(s) found\n" % (filename, len(zlist)) print "index |".rjust(13), " selector\n", "".rjust(30, '-') zlist.sort(key=lambda entry: int(entry[0]) if entry[0].isdigit() else entry[0]) for entry in zlist: print entry[0].rjust(10), "".rjust(3), for selector in entry[1]: if selector != entry[1][0]: print "".rjust(14), print selector.selectorText print "" else: print "%s: No z-index declarations found" % filename
def csscombine(path=None, url=None, sourceencoding=None, targetencoding=None, minify=True): """Combine sheets referred to by @import rules in given CSS proxy sheet into a single new sheet. :returns: combined cssText, normal or minified :Parameters: `path` or `url` path or URL to a CSSStyleSheet which imports other sheets which are then combined into one sheet `targetencoding` encoding of the combined stylesheet, default 'utf-8' `minify` defines if the combined sheet should be minified, default True """ cssutils.log.info(u"Combining files from %r" % url, neverraise=True) if sourceencoding is not None: cssutils.log.info(u"Using source encoding %r" % sourceencoding, neverraise=True) if path: src = cssutils.parseFile(path, encoding=sourceencoding) elif url: src = cssutils.parseUrl(url, encoding=sourceencoding) else: sys.exit("Path or URL must be given") result = cssutils.resolveImports(src) result.encoding = targetencoding cssutils.log.info(u"Using target encoding: %r" % targetencoding, neverraise=True) if minify: # save old setting and use own serializer oldser = cssutils.ser cssutils.setSerializer(cssutils.serialize.CSSSerializer()) cssutils.ser.prefs.useMinified() cssText = result.cssText cssutils.setSerializer(oldser) else: cssText = result.cssText return cssText
import cssutils import logging cssutils.log.setLevel(logging.CRITICAL) fd = open('fa_string.xml', 'w') fd.write('<?xml version="1.0" encoding="utf-8"?>\n') fd.write('<resources>\n') style = cssutils.parseFile('fontawesome.css') for rule in style: if rule.type == rule.STYLE_RULE: property = rule.style.getProperty('content') if property is not None: name = rule.selectorText.strip('.').replace('-', '_').replace( ':before', '') value = ascii(property.propertyValue[0].value).strip('\'').replace( '\\u', '&#x') + ';' fd.write('\t<string name="' + name + '">' + value + '</string>\n') fd.write('</resources>\n') fd.close()
cu.log.setLevel(logging.CRITICAL) #Giving a shorter name to the name-to-hex dictionary nth = wc.CSS2_NAMES_TO_HEX #I'll keep the next few lines in for now, shows how I figured out how to only #convert a color value to hex if there's a hex representation for that value # blue = 'blue' # blurb = 'blurb' # if blue in nth: # print(nth[blue]) # if blurb in nth: # print(nth[blurb]) #Read from the css file provided inbound_file = cu.parseFile('main.css') #For each rule in our file... for rule in inbound_file.cssRules: #If it's a style rule... if rule.type == rule.STYLE_RULE: #Then check out the properties it has for property in rule.style: #And if it's either color or background-color and has a name-to-hex value if (property.name == 'color' or property.name == 'background-color') and property.value in nth: #Then change it's value to the hex value property.value = nth[property.value] #Get a new file ready to write to outbound_file = open("new_main.css", "w")
#!/usr/bin/python3 import sys import logging import cssutils cssutils.log.setLevel(logging.CRITICAL) parser = cssutils.parseFile(sys.argv[1]) orig1 = '#7289da' orig2 = '#5b6dae' for rule in parser.cssRules: try: if orig1 in rule.cssText: print(rule.cssText.replace(orig1, sys.argv[2])) if orig2 in rule.cssText: print(rule.cssText.replace(orig2, sys.argv[3])) except TypeError: pass
def bigRedGoRunnable(self): self.rotationSpeed() self.startTime() self.endTime() if len(self.cssFileName.actValue.strip()) == 0: self.qem.showMessage("Error, no CSS file chosen.") if len(self.movieName.actValue.strip()) == 0: self.qem.showMessage("Error, no movie directory chosen.") # ## self.rotationSpeedDialog.setEnabled(False) self.rotationSpeedSlider.setEnabled(False) self.startTimeSlider.setEnabled(False) self.startTimeDialog.setEnabled(False) self.endTimeSlider.setEnabled(False) self.endTimeDialog.setEnabled(False) self.movieButton.setEnabled(False) self.cssButton.setEnabled(False) self.bigRedGoButton.setEnabled(False) # ## movieDir = self.movieName.actValue.strip() if not os.path.exists(movieDir): os.mkdir(movieDir) cssFileName = self.cssFileName.actValue.strip() css = cssutils.parseFile(cssFileName) self.cwa.pushNewColorsFromCSS(css) indices_up, indices_down, indices_upagain, upValue, downValue = self.get_indices( self.cwa.hsvs) def maxIndex(): currIdx = 0 for idx in xrange(int(30 * 0.01 * self.startTimeSlider.value())): currIdx += 1 for idx in indices_up: currIdx += 1 for idx in xrange(int(30 * 0.01 * self.endTimeSlider.value())): currIdx += 1 for idx in indices_down: currIdx += 1 if len(indices_upagain) != 0: for idx in xrange(int(30 * 0.01 * self.endTimeSlider.value())): currIdx += 1 for idx in indices_upagain: currIdx += 1 for idx in xrange(int(30 * 0.01 * self.startTimeSlider.value())): currIdx += 1 return currIdx self.maxIndex = maxIndex() widgets = [ 'Progress: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA() ] self.cmdlinepbar = ProgressBar(widgets=widgets, maxval=self.maxIndex).start() if logging.getLogger().isEnabledFor(logging.DEBUG): logdir = os.path.join(os.path.expanduser('~/temp'), 'debugdir') if os.path.isdir(logdir): shutil.rmtree(logdir) os.mkdir(logdir) # ## self.runGoRun = CustomRunnable(self) self.runGoRun.partDone.connect(self._updateColorWheel) self.runGoRun.finished.connect(self._createMovieAndStop) self.runGoRun.start()
def test_parseFile(self): "cssutils.parseFile()" # name if used with open, href used for @import resolving name = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'sheets', 'import.css') href = cssutils.helper.path2url(name) s = cssutils.parseFile(name, href=href, media='screen', title='from file') self.assertTrue(isinstance(s, cssutils.css.CSSStyleSheet)) if sys.platform.startswith('java'): # on Jython only file: self.assertTrue(s.href.startswith('file:')) else: # normally file:/// on win and file:/ on unix self.assertTrue(s.href.startswith('file:/')) self.assertTrue(s.href.endswith('/sheets/import.css')) self.assertEqual(u'utf-8', s.encoding) self.assertEqual(u'screen', s.media.mediaText) self.assertEqual(u'from file', s.title) self.assertEqual(self.exp.encode(), s.cssText) ir = s.cssRules[0] self.assertEqual('import/import2.css', ir.href) irs = ir.styleSheet self.assertTrue(isinstance(irs, cssutils.css.CSSStyleSheet)) self.assertEqual( irs.cssText, '@import "../import3.css";\n@import "import-impossible.css" print;\n.import2 {\n /* sheets/import2.css */\n background: url(http://example.com/images/example.gif);\n background: url(//example.com/images/example.gif);\n background: url(/images/example.gif);\n background: url(images2/example.gif);\n background: url(./images2/example.gif);\n background: url(../images/example.gif);\n background: url(./../images/example.gif)\n }' .encode()) # name is used for open and setting of href automatically # test needs to be relative to this test file! os.chdir(os.path.dirname(__file__)) name = os.path.join('..', '..', '..', 'sheets', 'import.css') s = cssutils.parseFile(name, media='screen', title='from file') self.assertTrue(isinstance(s, cssutils.css.CSSStyleSheet)) if sys.platform.startswith('java'): # on Jython only file: self.assertTrue(s.href.startswith('file:')) else: # normally file:/// on win and file:/ on unix self.assertTrue(s.href.startswith('file:/')) self.assertTrue(s.href.endswith('/sheets/import.css')) self.assertEqual(u'utf-8', s.encoding) self.assertEqual(u'screen', s.media.mediaText) self.assertEqual(u'from file', s.title) self.assertEqual(self.exp.encode(), s.cssText) ir = s.cssRules[0] self.assertEqual('import/import2.css', ir.href) irs = ir.styleSheet self.assertTrue(isinstance(irs, cssutils.css.CSSStyleSheet)) self.assertEqual( irs.cssText, '@import "../import3.css";\n@import "import-impossible.css" print;\n.import2 {\n /* sheets/import2.css */\n background: url(http://example.com/images/example.gif);\n background: url(//example.com/images/example.gif);\n background: url(/images/example.gif);\n background: url(images2/example.gif);\n background: url(./images2/example.gif);\n background: url(../images/example.gif);\n background: url(./../images/example.gif)\n }' .encode()) # next test css = u'a:after { content: "羊蹄€\u2020" }' fd, name = tempfile.mkstemp('_cssutilstest.css') t = os.fdopen(fd, 'wb') t.write(css.encode('utf-8')) t.close() self.assertRaises(UnicodeDecodeError, cssutils.parseFile, name, 'ascii') # ??? s = cssutils.parseFile(name, encoding='iso-8859-1') self.assertEqual(cssutils.css.CSSStyleSheet, type(s)) self.assertEqual(s.cssRules[1].selectorText, 'a:after') s = cssutils.parseFile(name, encoding='utf-8') self.assertEqual(cssutils.css.CSSStyleSheet, type(s)) self.assertEqual(s.cssRules[1].selectorText, 'a:after') css = u'@charset "iso-8859-1"; a:after { content: "ä" }' t = codecs.open(name, 'w', 'iso-8859-1') t.write(css) t.close() self.assertRaises(UnicodeDecodeError, cssutils.parseFile, name, 'ascii') s = cssutils.parseFile(name, encoding='iso-8859-1') self.assertEqual(cssutils.css.CSSStyleSheet, type(s)) self.assertEqual(s.cssRules[1].selectorText, 'a:after') self.assertRaises(UnicodeDecodeError, cssutils.parseFile, name, 'utf-8') # clean up try: os.remove(name) except OSError, e: pass
# -*- coding: utf-8 -*- import cssutils import sys #print (str(sys.argv[1])) # Parse the stylesheet, replace color parser = cssutils.parseFile('style.css') for rule in parser.cssRules: try: if rule.selectorText == '#ab': #rule.style.backgroundColor = str(sys.argv[1]) # Replace background rule.style.color = str(sys.argv[1]) # Replace background rule.style.top = str(sys.argv[2]) # Replace top_to_text_distance rule.style.width = str(sys.argv[3]) # Replace width of text except AttributeError as e: pass # Ignore error if the rule does not have background # Write to a new file with open('style_new.css', 'wb') as f: f.write(parser.cssText)
def _load_selected(self, new_path=None): if new_path is None: self._css_path = self._determine_theme_path() else: self._css_path = new_path self._css = cssutils.parseFile(self._css_path)
def _load_default(self): self._default_css_path = self.get_theme_path('default', user=False) self._default_css = cssutils.parseFile(self._default_css_path)
def _load_pre(self, theme): log.info('Preload theme %s', theme) self._pre_css_path = self.get_theme_path(theme) self._pre_css = cssutils.parseFile(self._pre_css_path)
def get_parse_file(file_path): return cssutils.parseFile(file_path)
for i in range(len(a)): directory = a[i]['href'] if(".css" not in directory): print("-------Skipped for ---------",directory) continue if "http" in directory or "https" in directory: print ("------Skipped for ----- ",directory) continue print ('\t[+]Getting CSS = '+str(directory)) if "/" not in directory: print ("\tNo directory. Saving file",directory) elif not os.path.exists(os.path.dirname(directory)): print (" [DIR]Creating directory") os.makedirs(os.path.dirname(directory)) testfile, headers = urlretrieve(baseurl+directory, directory, reporthook=report) urls = list( cssutils.getUrls(cssutils.parseFile(directory))) if(len(urls)!=0): for link in urls: try: if "http" in directory or "https" in link or "data:image/" in link: print ("------Skipped for ----- ",link) continue while("../" in link): if("assets" in link): link = link[3:] else: link = "assets/"+link[3:] print ('\t\t[+]Getting CSS-Image = '+str(link)) if "/" not in link: print ("\t\tNo directory. Saving file",link) elif not os.path.exists(os.path.dirname(link)):
metavar='output', help='HTML preview filename') parser.add_argument('--no-frames', '-nf', default=False, action='store_true', help='Do NOT wrap fixed/absolute elements in iframe') args = parser.parse_args(sys.argv[1:]) output_file = args.output_file and open(args.output_file, 'w') or sys.stdout already_seen = [] sheet = cssutils.parseFile(args.css_file) print('Generating HTML preview. Please wait...', file=sys.stderr) print(f'''<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CSS preview: {args.css_file}</title> <link href="{args.css_file}" rel="stylesheet" type="text/css" /> </head> <body> ''', file=output_file) selectors_requiring_iframe = []
def read_bootstrap_rules(bootstrap_path): # read in bootstrap rules bs_style_sheet = BootstrapStyleSheet() for rule in cssutils.parseFile(bootstrap_path): bs_style_sheet.add_rule(rule) return bs_style_sheet
def transform(self, pretty_print=True): """change the self.html and return it with CSS turned into style attributes. """ if etree is None: return self.html tree = etree.fromstring(self.html.strip()).getroottree() page = tree.getroot() cssutils.ser.prefs.useMinified() cssutils.ser.prefs.keepAllProperties = False if page is None: print repr(self.html) raise PremailerError("Could not parse the html") assert page is not None ## ## style selectors ## self.styles = defaultdict(list) for style in CSSSelector('style')(page): css_body = etree.tostring(style) css_body = css_body.split('>')[1].split('</')[0] leftovers = self._parse_stylesheet(page, cssutils.parseString(css_body)) if leftovers: style.text = '\n'.join([r.cssText for r in leftovers]) elif not self.keep_style_tags: parent_of_style = style.getparent() parent_of_style.remove(style) for stylefile in self.external_styles: if stylefile.startswith('http://'): self._parse_stylesheet(page, cssutils.parseUrl(stylefile)) elif os.path.exists(stylefile): self._parse_stylesheet(page, cssutils.parseFile(stylefile)) else: raise ValueError(u'Could not find external style: %s' % \ stylefile) for element, rules in self.styles.iteritems(): rules += [element.attrib.get('style', '')] declarations = [] pseudoclass_rules = defaultdict(list) for rule in rules: if not rule: continue elif isinstance(rule, tuple): # pseudoclass pseudoclass, prules = rule pseudoclass_rules[pseudoclass].append(prules) else: declarations.append(rule.strip(';')) css_text = ';'.join(declarations) style = cssutils.parseStyle(css_text) if pseudoclass_rules: prules_list = [] for pclass, prules in pseudoclass_rules.iteritems(): pdecl = cssutils.parseStyle(';'.join(prules)) prules_list.append(':%s{%s}' % (pclass, pdecl.cssText)) if css_text: element.attrib['style'] = '{%s} %s' % \ (style.cssText, ' '.join(prules_list)) else: element.attrib['style'] = ' '.join(prules_list) else: element.attrib['style'] = style.cssText self._style_to_basic_html_attributes(element, style) # now we can delete all 'class' attributes (that aren't in the # whitelist) for item in page.xpath('//*[@class]'): classes = set(item.attrib['class'].split()) remaining_classes = classes - (classes ^ self.keep_classnames) if len(remaining_classes) == 0: del item.attrib['class'] else: item.attrib['class'] = ' '.join(remaining_classes) ## ## URLs ## if self.base_url: for attr in ('href', 'src'): for item in page.xpath('//*[@%s]' % attr): if attr == 'href' and self.preserve_internal_links \ and item.attrib[attr].startswith('#'): continue item.attrib[attr] = urlparse.urljoin( self.base_url, item.attrib[attr]) return etree.tostring(page, pretty_print=pretty_print) \ .replace('<head/>', '<head></head>')
name = os.path.join(os.path.dirname(__file__), '..', 'sheets', 'import.css') #href = 'file:' + urllib.pathname2url(name) from nturl2path import pathname2url href = pathname2url(os.path.abspath(name)) href = href.replace('|', ':') href = href[3:] href = 'file:' + href href = jyhref(name) href = None print(name, href) s = cssutils.parseFile(name, href=href, media='screen', title='from file') print(0, s) print(1, s.cssRules[0].styleSheet) print(2, s.cssRules[0].styleSheet.cssText) sys.exit(0) if 1: from cssutils.script import csscombine #a = csscombine(url='http://localhost/css.css', targetencoding='iso-8859-1', minify=False) print() b = csscombine(r"E:\xampp\htdocs\css.css", targetencoding='iso-8859-1', minify=False) #print a print(b)
# Parse the CSS code into a useful data structure that allows you to iterate through the style rules and isolate the property # (e.g. 'color', 'background-color') from the value (e.g. 'palegoldenrod') # Automatically convert the named CSS colour into a hex code string # Put it back together into a string # Save the results into a new .css file # Libraries to use # Use the Python standard library to open and read the CSS file, and to save to a new file at the end (steps 1 and 5) # Use cssutils to parse the contents of the file (steps 2 and 4) # Use webcolors to convert from colour name to hex code (step 3) import cssutils import webcolors # stylesheet = open('main.css','w+') sheet = cssutils.parseFile('main.css') for rule in sheet: if rule.type == rule.STYLE_RULE: for property in rule.style: if property.name == 'color': if property.value[0] != '#': if property.value not in ['inherit']: print(property.value) print(webcolors.CSS3_NAMES_TO_HEX[property.value]) property.value = ( webcolors.CSS3_NAMES_TO_HEX[property.value]) # Write to a new file with open('style_new.css', 'wb') as f: f.write(sheet.cssText)
#!/usr/bin/env python # Uses PyWal colors and adds them to a predefined Albert launcher theme __author__ = "ErkHal" import os import json import cssutils #Edit these to change the color variables assigned to the QSS rules SELECTION_COLOR = 'color6' pywalFilepath = os.path.join(os.environ['HOME'], '.cache/wal/colors.json') styleSheet = cssutils.parseFile( '/usr/share/albert/org.albert.frontend.widgetboxmodel/themes/Walbert.qss') #Load pywal JSON properties with open(pywalFilepath) as f: colorArray = json.load(f) for rule in styleSheet.cssRules: try: if rule.selectorText == '*': rule.style.color = colorArray['special']['foreground'] rule.style.backgroundColor = colorArray['special']['background'] if rule.selectorText == '#settingsButton': rule.style.color = colorArray['colors'][SELECTION_COLOR] if rule.selectorText == '#frame' or rule.selectorText == '#inputLine': rule.style.backgroundColor = colorArray['special']['background']
def run(*args): logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) sheet = cssutils.parseFile('static/css/base.css') selector_coloring = {} for rule in sheet: if hasattr(rule, 'selectorText'): selector = rule.selectorText.lstrip('.') color = rule.style.getPropertyValue('color') if color and re.match('#[0-9A-Za-z]', color): color = color.lstrip('#') if len(color) == 3: color = ''.join(a + b for a, b in zip(color, color)) color = '#' + color assert selector not in selector_coloring or selector_coloring.get( selector) == color selector_coloring[selector] = color for resource in Resource.objects.all(): if not resource.ratings: continue to_save = False prev_rgb = None hsl = None for rating in resource.ratings: cls = f'coder-{rating["color"]}' if 'rgb' in rating: rating.pop('rgb') if 'hsv' in rating: rating.pop('hsv') hex_rgb = selector_coloring[cls] if rating.get('hex_rgb') != hex_rgb: rating['hex_rgb'] = hex_rgb to_save = True rgb = [int(hex_rgb[i:i + 2], 16) / 255 for i in range(1, 6, 2)] H, L, S = [round(x, 2) for x in colorsys.rgb_to_hls(*rgb)] if prev_rgb == hex_rgb: H, S, L = hsl L *= 0.75 hsl = [H, S, L] if rating.get('hsl') != hsl: rating['hsl'] = hsl to_save = True prev_rgb = hex_rgb limit = None for rating in reversed(resource.ratings[:-1]): if limit is None or rating['color'] != limit['color']: limit = rating value = limit['high'] + 1 if rating.get('next') != value: rating['next'] = value to_save = True limit = None for rating in resource.ratings[:-1]: if limit is None or rating['color'] != limit['color']: limit = rating value = limit['low'] if rating.get('prev') != value: rating['prev'] = value to_save = True if to_save: pprint(resource.ratings) resource.save()
import cssutils import urllib css_path = "styles.css" base_url = "https://www.test.com" file_dest = "C:/images/" sheet = cssutils.parseFile(css_path) for rule in sheet: if hasattr( rule, 'style' ) and rule.style.backgroundImage != '' and 'url' in rule.style.backgroundImage: file_name = rule.style.backgroundImage.split('/')[2].replace( ')', '').replace("'", "") file_url = base_url + file_name out_loc = file_dest + file_name urllib.request.urlretrieve(file_url, out_loc)
'header': '#F44336', 'article': '#FFCDD2', 'nav a:hover': '#2196F3' }, } color_theme = color_themes[color_theme] for rule in css_template: if rule.type == rule.STYLE_RULE: if rule.selectorText in color_theme.keys(): rule.style['background-color'] = color_theme[rule.selectorText] # build index.html from template and articles and write to target with open(template_html) as input_file: html_template = parse_html(input_file.read(), 'html5lib') html_template.section.append(html_articles) with open(target_html, 'w') as output_file: output_file.write(html_template.prettify(formatter='html5')) with open(template_css) as input_file: css_template = css.parseFile(template_css) apply_color_theme(css_template, 'BlueGrey') with open(target_css, 'wb') as output_file: output_file.write(css_template.cssText) # copy css template to target #shutil.copyfile(template_css, target_css) shutil.copyfile(template_js, target_js)