How to use the cssutils.CSSParser function in cssutils

To help you get started, we’ve selected a few cssutils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jorgebastida / cssbuster / cssbuster.py View on Github external
"the css and the images."))

    css_path = os.path.basename(args[0])
    img_rel_path = args[1]

    # Configure the logger
    log = logging.getLogger('csscache')
    handler = logging.StreamHandler(sys.stderr)
    handler.setLevel(logging.ERROR)
    log.addHandler(handler)

    if options.minified:
        cssutils.ser.prefs.useMinified()

    # Create the parser
    parser = cssutils.CSSParser(log=log,
                                raiseExceptions=True,
                                parseComments=not options.minified,
                                validate=False)
    try:
        # Parse the original file
        sheet = parser.parseFile(args[0])
    except Exception, e:
        sys.stderr.write('Error: %s %s\n' % (css_path, e.args[0]))
        sys.exit(1)

    # Replace all the urls
    replacer = partial(cache_bust_replacer, options, css_path, img_rel_path)
    cssutils.replaceUrls(sheet, replacer, ignoreImportRules=True)

    # print the new css
    sys.stdout.write(sheet.cssText)
github qutebrowser / qutebrowser / qutebrowser / browser / webkit / mhtml.py View on Github external
Args:
        data: The content of the stylesheet to scan as string.
        inline: True if the argument is an inline HTML style attribute.
    """
    try:
        import cssutils
    except (ImportError, re.error):
        # Catching re.error because cssutils in earlier releases (<= 1.0) is
        # broken on Python 3.5
        # See https://bitbucket.org/cthedot/cssutils/issues/52
        return None

    # We don't care about invalid CSS data, this will only litter the log
    # output with CSS errors
    parser = cssutils.CSSParser(loglevel=100,
                                fetcher=lambda url: (None, ""), validate=False)
    if not inline:
        sheet = parser.parseString(data)
        return list(cssutils.getUrls(sheet))
    else:
        urls = []
        declaration = parser.parseStyle(data)
        # prop = background, color, margin, ...
        for prop in declaration:
            # value = red, 10px, url(foobar), ...
            for value in prop.propertyValue:
                if isinstance(value, cssutils.css.URIValue):
                    if value.uri:
                        urls.append(value.uri)
        return urls
github johnfraney / django-bootstrap-customizer / bootstrap_customizer / utils.py View on Github external
def extract_bootstrap_vendor_prefix_rules():
    """
    Returns vendor-prefixed properties from Bootstrap's compiled CSS
    """
    vendor_prefix_rules = {}
    bootstrap_css_file_path = finders.find('bootstrap/dist/css/bootstrap.min.css')
    parser = cssutils.CSSParser(validate=False)
    sheet = parser.parseString(open(bootstrap_css_file_path, 'r').read())
    vendor_prefix_rules = {}
    for rule in sheet:
        if not rule.type == rule.STYLE_RULE:
            continue
        for property in rule.style:
            if property.name.startswith('-'):
                if vendor_prefix_rules.get(rule.selectorText, None) is None:
                    vendor_prefix_rules[rule.selectorText] = []
                vendor_prefix_rules[rule.selectorText].append(property)

    return vendor_prefix_rules
github hsoft / pdfmasher / ebooks / oeb / stylizer.py View on Github external
else:
            decoded_path = path
        self.oeb = oeb
        self.profile = profile
        self.change_justification = change_justification
        item = oeb.manifest.hrefs[path]
        basename = os.path.basename(decoded_path)
        cssname = os.path.splitext(basename)[0] + '.css'
        stylesheets = [html_css_stylesheet()]
        head = xpath(tree, '/h:html/h:head')
        if head:
            head = head[0]
        else:
            head = []

        parser = CSSParser(fetcher=self._fetch_css_file,
                log=logging.getLogger('calibre.css'))
        self.font_face_rules = []
        for elem in head:
            if (elem.tag == XHTML('style') and
                elem.get('type', CSS_MIME) in OEB_STYLES):
                text = elem.text if elem.text else ''
                for x in elem:
                    t = getattr(x, 'text', None)
                    if t:
                        text += '\n\n' + force_unicode(t, 'utf-8')
                    t = getattr(x, 'tail', None)
                    if t:
                        text += '\n\n' + force_unicode(t, 'utf-8')
                if text:
                    text = XHTML_CSS_NAMESPACE + elem.text
                    text = oeb.css_preprocessor(text)
github merengue-cms / merengueproj / merengueproj / merengue / section / fields.py View on Github external
def clean(self, value):
        clean_value = super(CSSValidatorField, self).clean(value)
        mylog = StringIO.StringIO()
        h = logging.StreamHandler(mylog)
        h.setFormatter(logging.Formatter('%(levelname)s %(message)s'))
        cssutils.log.addHandler(h)
        cssutils.log.setLevel(logging.INFO)
        parser = cssutils.CSSParser(raiseExceptions=True)
        try:
            value_parse = parser.parseString(clean_value)
        except SyntaxErr, e:
            error_message = getattr(e, 'msg', e.message)
            raise ValidationError(_('Syntax Error %s' % error_message.replace('\\n', '').replace('\\r', '')))
        if self.request.POST.get('%s_normalize' % self.name, None):
            clean_value = value_parse.cssText
        if self.request.POST.get('%s_show_all_errors' % self.name, None):
            errors_and_warning = mylog.getvalue()
            if errors_and_warning:
                raise ValidationError(errors_and_warning)
        return clean_value
github palexu / send2kindle / calibre / ebooks / oeb / base.py View on Github external
def _parse_css(self, data):
            from cssutils import CSSParser, log, resolveImports
            log.setLevel(logging.WARN)
            log.raiseExceptions = False
            self.oeb.log.debug('Parsing %s...' % self.href)
            data = self.oeb.decode(data)
            data = self.oeb.css_preprocessor(data, add_namespace=True)
            parser = CSSParser(loglevel=logging.WARNING,
                               fetcher=self.override_css_fetch or self._fetch_css,
                               log=_css_logger)
            data = parser.parseString(data, href=self.href, validate=False)
            data = resolveImports(data)
            data.namespaces['h'] = XHTML_NS
            return data
github roverdotcom / django-inlinecss / django_inlinecss / pynliner / __init__.py View on Github external
def _get_styles(self):
        """Gets all CSS content from and removes all  and
        <style> tags concatenating into one CSS string which is then parsed with
        cssutils and the resulting CSSStyleSheet object set to
        `self.stylesheet`.
        """
        self._get_external_styles()
        self._get_internal_styles()

        cssparser = cssutils.CSSParser(log=self.log)
        self.stylesheet = cssparser.parseString(self.style_string)
</style>
github palexu / send2kindle / calibre / ebooks / oeb / base.py View on Github external
else:
                del el.attrib[attrib]
            continue
        if attrib is None:
            new = el.text[:pos] + new_link + el.text[pos+len(link):]
            el.text = new
        else:
            cur = el.attrib[attrib]
            if not pos and len(cur) == len(link):
                # Most common case
                el.attrib[attrib] = new_link
            else:
                new = cur[:pos] + new_link + cur[pos+len(link):]
                el.attrib[attrib] = new

    parser = CSSParser(raiseExceptions=False, log=_css_logger,
            fetcher=lambda x:(None, None))
    for el in root.iter(etree.Element):
        try:
            tag = el.tag
        except UnicodeDecodeError:
            continue

        if tag == XHTML('style') and el.text and \
                (_css_url_re.search(el.text) is not None or '@import' in
                        el.text):
            stylesheet = parser.parseString(el.text, validate=False)
            replaceUrls(stylesheet, link_repl_func)
            repl = stylesheet.cssText
            if isbytestring(repl):
                repl = repl.decode('utf-8')
            el.text = '\n'+ repl + '\n'
github kovidgoyal / calibre / src / calibre / ebooks / oeb / stylizer.py View on Github external
def __init__(self, tree, path, oeb, profile=PROFILES['PRS505'],
            extra_css='', user_css=''):
        self.oeb = oeb
        self.profile = profile
        self.logger = oeb.logger
        item = oeb.manifest.hrefs[path]
        basename = os.path.basename(path)
        cssname = os.path.splitext(basename)[0] + '.css'
        stylesheets = [HTML_CSS_STYLESHEET]
        head = xpath(tree, '/h:html/h:head')[0]
        parser = cssutils.CSSParser(fetcher=self._fetch_css_file,
                log=logging.getLogger('calibre.css'))
        self.font_face_rules = []
        for elem in head:
            if elem.tag == XHTML('style') and elem.text \
               and elem.get('type', CSS_MIME) in OEB_STYLES:
                text = XHTML_CSS_NAMESPACE + elem.text
                stylesheet = parser.parseString(text, href=cssname)
                stylesheet.namespaces['h'] = XHTML_NS
                stylesheets.append(stylesheet)
            elif elem.tag == XHTML('link') and elem.get('href') \
                 and elem.get('rel', 'stylesheet') == 'stylesheet' \
                 and elem.get('type', CSS_MIME) in OEB_STYLES:
                href = urlnormalize(elem.attrib['href'])
                path = item.abshref(href)
                sitem = oeb.manifest.hrefs.get(path, None)
                if sitem is None:
github qutebrowser / qutebrowser / qutebrowser / browser / webkit / mhtml.py View on Github external
Args:
        data: The content of the stylesheet to scan as string.
        inline: True if the argument is an inline HTML style attribute.
    """
    try:
        import cssutils
    except (ImportError, re.error):
        # Catching re.error because cssutils in earlier releases (&lt;= 1.0) is
        # broken on Python 3.5
        # See https://bitbucket.org/cthedot/cssutils/issues/52
        return None

    # We don't care about invalid CSS data, this will only litter the log
    # output with CSS errors
    parser = cssutils.CSSParser(loglevel=100,
                                fetcher=lambda url: (None, ""), validate=False)
    if not inline:
        sheet = parser.parseString(data)
        return list(cssutils.getUrls(sheet))
    else:
        urls = []
        declaration = parser.parseStyle(data)
        # prop = background, color, margin, ...
        for prop in declaration:
            # value = red, 10px, url(foobar), ...
            for value in prop.propertyValue:
                if isinstance(value, cssutils.css.URIValue):
                    if value.uri:
                        urls.append(value.uri)
        return urls