How to use the cssutils.css.CSSStyleSheet 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 tito / pymt / pymt / lib / cssutils / parse.py View on Github external
:param href:
            The ``href`` attribute to assign to the parsed style sheet.
            Used to resolve other urls in the parsed sheet like @import hrefs.
        :param media:
            The ``media`` attribute to assign to the parsed style sheet
            (may be a MediaList, list or a string).
        :param title:
            The ``title`` attribute to assign to the parsed style sheet.
        :returns:
            :class:`~cssutils.css.CSSStyleSheet`.
        """
        self.__parseSetting(True)
        if isinstance(cssText, str):
            cssText = codecs.getdecoder('css')(cssText, encoding=encoding)[0]

        sheet = cssutils.css.CSSStyleSheet(href=href,
                                           media=cssutils.stylesheets.MediaList(media),
                                           title=title)
        sheet._setFetcher(self.__fetcher)
        # tokenizing this ways closes open constructs and adds EOF
        sheet._setCssTextWithEncodingOverride(self.__tokenizer.tokenize(cssText,
                                                                        fullsheet=True),
                                              encodingOverride=encoding)
        self.__parseSetting(False)
        return sheet

github muccg / yabi / yabi / yabi / preview / css.py View on Github external
def _sanitise(content, parser=default_parser, ruleset=default_ruleset):
    """
    The actual implementation of the CSS sanitiser.
    """

    input = parser.parseString(content)
    output = css.CSSStyleSheet()

    def primitive(value):
        # This is the one place where we'll blacklist rather than whitelist:
        # all of the primitive types defined by cssutils are safe except for
        # URIs and "unknowns" (which includes IE's Javascript expression syntax
        # and filter values).
        if not isinstance(value, css.URIValue):
            return value.cssText

        return ""

    def rule(input_rule):
        # Non-style elements are presently stripped. We may want to maintain
        # comments at some point, but for now we'll only pass the barest
        # structural elements that we're sure are safe through.
        if input_rule.type == input_rule.STYLE_RULE:
github kovidgoyal / calibre / src / cssutils / css / cssmediarule.py View on Github external
unparsable.

        """
        self._checkReadonly()

        # check position
        if index is None:
            index = len(self._cssRules)
        elif index < 0 or index > self._cssRules.length:
            raise xml.dom.IndexSizeErr(
                u'CSSMediaRule: Invalid index %s for CSSRuleList with a length of %s.' % (
                    index, self._cssRules.length))

        # parse
        if isinstance(rule, basestring):
            tempsheet = cssutils.css.CSSStyleSheet()
            tempsheet.cssText = rule
            if len(tempsheet.cssRules) != 1 or (tempsheet.cssRules and
             not isinstance(tempsheet.cssRules[0], cssutils.css.CSSRule)):
                self._log.error(u'CSSMediaRule: Invalid Rule: %s' % rule)
                return
            rule = tempsheet.cssRules[0]
            
        elif isinstance(rule, cssutils.css.CSSRuleList):
            # insert all rules
            for i, r in enumerate(rule):
                self.insertRule(r, index + i)
            return index
            
        elif not isinstance(rule, cssutils.css.CSSRule):
            self._log.error(u'CSSMediaRule: Not a CSSRule: %s' % rule)
            return
github tito / pymt / pymt / lib / cssutils / css / cssmediarule.py View on Github external
unparsable.

        """
        self._checkReadonly()

        # check position
        if index is None:
            index = len(self.cssRules)
        elif index < 0 or index > self.cssRules.length:
            raise xml.dom.IndexSizeErr(
                u'CSSMediaRule: Invalid index %s for CSSRuleList with a length of %s.' % (
                    index, self.cssRules.length))

        # parse
        if isinstance(rule, basestring):
            tempsheet = cssutils.css.CSSStyleSheet()
            tempsheet.cssText = rule
            if len(tempsheet.cssRules) != 1 or (tempsheet.cssRules and
             not isinstance(tempsheet.cssRules[0], cssutils.css.CSSRule)):
                self._log.error(u'CSSMediaRule: Invalid Rule: %s' % rule)
                return
            rule = tempsheet.cssRules[0]
        elif not isinstance(rule, cssutils.css.CSSRule):
            self._log.error(u'CSSMediaRule: Not a CSSRule: %s' % rule)
            return

        # CHECK HIERARCHY
        # @charset @import @page @namespace @media
        if isinstance(rule, cssutils.css.CSSCharsetRule) or \
           isinstance(rule, cssutils.css.CSSFontFaceRule) or \
           isinstance(rule, cssutils.css.CSSImportRule) or \
           isinstance(rule, cssutils.css.CSSNamespaceRule) or \
github lavr / python-emails / emails / loader / cssinliner.py View on Github external
def __init__(self, base_url=None, css=None):

        self.stylesheet = CSSStyleSheet(href=base_url)
        self.base_url = base_url
        if css:
            self.add_css(css)
github lavr / python-emails / emails / loader / stylesheets.py View on Github external
def _concatenate_sheets(self):
        if self.dirty or (self._cached_stylesheet is None):
            r = CSSStyleSheet()
            uri_properties = []

            for d in self.sheets:
                local_loader = d.get('local_loader', None)
                text = d.get('text', None)
                uri = d.get('uri', None)
                absolute_url = d.get('absolute_url', None)

                if (text is None) and local_loader and uri:
                    text = local_loader[uri]

                if text:
                    sheet = CSSParser().parseString(text, href=absolute_url)
                else:
                    sheet = cssutils.parseUrl(href=absolute_url)
github palexu / send2kindle / cssutils / parse.py View on Github external
If given defines if validation is used. Uses CSSParser settings as
            fallback
        :returns:
            :class:`~cssutils.css.CSSStyleSheet`.
        """
        self.__parseSetting(True)
        # TODO: py3 needs bytes here!
        # modify by arroz, 
        if isinstance(cssText, bytes) and encoding:
            cssText = codecs.decode(cssText, encoding)
            #cssText = codecs.getdecoder('css')(cssText, encoding=encoding)[0]

        if validate is None:
            validate = self._validate
            
        sheet = cssutils.css.CSSStyleSheet(href=href,
                                           media=cssutils.stylesheets.MediaList(media),
                                           title=title,
                                           validating=validate)
        sheet._setFetcher(self.__fetcher)
        # tokenizing this ways closes open constructs and adds EOF
        sheet._setCssTextWithEncodingOverride(self.__tokenizer.tokenize(cssText,
                                                                        fullsheet=True),
                                              encodingOverride=encoding)
        self.__parseSetting(False)
        return sheet
github kovidgoyal / calibre / src / cssutils / parse.py View on Github external
:param href:
            The ``href`` attribute to assign to the parsed style sheet.
            Used to resolve other urls in the parsed sheet like @import hrefs.
        :param media:
            The ``media`` attribute to assign to the parsed style sheet
            (may be a MediaList, list or a string).
        :param title:
            The ``title`` attribute to assign to the parsed style sheet.
        :returns:
            :class:`~cssutils.css.CSSStyleSheet`.
        """
        self.__parseSetting(True)
        if isinstance(cssText, str):
            cssText = codecs.getdecoder('css')(cssText, encoding=encoding)[0]

        sheet = cssutils.css.CSSStyleSheet(href=href,
                                           media=cssutils.stylesheets.MediaList(media),
                                           title=title)
        sheet._setFetcher(self.__fetcher)
        # tokenizing this ways closes open constructs and adds EOF
        sheet._setCssTextWithEncodingOverride(self.__tokenizer.tokenize(cssText,
                                                                        fullsheet=True),
                                              encodingOverride=encoding)
        self.__parseSetting(False)
        return sheet
github lavr / python-emails / emails / loader / cssinliner.py View on Github external
media: optional
            TODO: view for which media it should be
        name: optional
            TODO: names of sheets only
        styleCallback: optional
            should return css.CSSStyleDeclaration of inline styles, for html
            a style declaration for ``element@style``. Gets one parameter
            ``element`` which is the relevant DOMElement

        returns style view
            a dict of {DOMElement: css.CSSStyleDeclaration} for html
        """

        styleCallback = styleCallback or self.styleattribute

        _unmergable_rules = CSSStyleSheet()

        view = {}
        specificities = {}  # needed temporarily

        # TODO: filter rules simpler?, add @media
        rules = (rule for rule in sheet if rule.type == rule.STYLE_RULE)
        for rule in rules:
            for selector in rule.selectorList:
                self.log(0, 'SELECTOR', selector.selectorText)
                # TODO: make this a callback to be able to use other stuff than lxml
                try:
                    cssselector = CSSSelector(selector.selectorText)
                except (ExpressionError, NotImplementedError) as e:
                    _unmergable_rules.add(CSSStyleRule(selectorText=selector.selectorText,
                                                       style=rule.style))
                    continue