How to use the cssutils.parseStyle 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 norbusan / calibre-debian / src / calibre / ebooks / oeb / normalize_css.py View on Github external
def test_border_condensation(self):
            vals = 'red solid 5px'
            css = '; '.join('border-%s-%s: %s' % (edge, p, v) for edge in EDGES for p, v in zip(BORDER_PROPS, vals.split()))
            style = parseStyle(css)
            condense_rule(style)
            for e, p in product(EDGES, BORDER_PROPS):
                self.assertFalse(style.getProperty('border-%s-%s' % (e, p)))
                self.assertFalse(style.getProperty('border-%s' % e))
                self.assertFalse(style.getProperty('border-%s' % p))
            self.assertEqual(style.getProperty('border').value, vals)
            css = '; '.join('border-%s-%s: %s' % (edge, p, v) for edge in ('top',) for p, v in zip(BORDER_PROPS, vals.split()))
            style = parseStyle(css)
            condense_rule(style)
            self.assertEqual(style.cssText, 'border-top: %s' % vals)
            css += ';' + '; '.join('border-%s-%s: %s' % (edge, p, v) for edge in ('right', 'left', 'bottom') for p, v in
                             zip(BORDER_PROPS, vals.replace('red', 'green').split()))
            style = parseStyle(css)
            condense_rule(style)
            self.assertEqual(len(style.getProperties()), 4)
            self.assertEqual(style.getProperty('border-top').value, vals)
github mushorg / snare / snare / html_handler.py View on Github external
async def handle_content(self, content):
        soup = BeautifulSoup(content, 'html.parser')
        if self.no_dorks is not True:
            for p_elem in soup.find_all('p'):
                if p_elem.findChildren():
                    continue
                css = None
                if 'style' in p_elem.attrs:
                    css = cssutils.parseStyle(p_elem.attrs['style'])
                text_list = p_elem.text.split()
                p_new = soup.new_tag('p', style=css.cssText if css else None)
                for idx, word in enumerate(text_list):
                    # Fetch dorks if required
                    if len(self.dorks) <= 0:
                        self.dorks = await self.get_dorks()
                    word += ' '
                    if idx % 5 == 0:
                        a_tag = soup.new_tag(
                            'a',
                            href=self.dorks.pop(),
                            style='color:{color};text-decoration:none;cursor:text;'.format(
                                color=css.color if css and 'color' in css.keys() else '#000000'
                            )
                        )
                        a_tag.string = word
github portnov / color-palette / palette-editor / palette / storage / html.py View on Github external
for tag, name, attrs in [(tag, tag.name, tag.attrs) for tag in soup.findChildren()]:
        for key, value in attrs:
            if key in [u"color", u"bgcolor", u"fgcolor"]:
                #cname = "_".join([name, key, value[1:]])
                css_color = parse_color(value)
                if not isinstance(css_color, cssutils.css.ColorValue):
                    continue
                old_color = convert_color(css_color).hex()
                cname = rev[old_color]
                if cname in new_colors:
                    new_color = new_colors[cname]
                    tag[key] = new_color.hex()
                    old_colors[cname] = new_color

            if key == u"style":
                style = cssutils.parseStyle(value)
                for property in style.getProperties():
                    for i, val in enumerate(property.propertyValue):
                        if not isinstance(val, cssutils.css.ColorValue):
                            continue
                        old_color = convert_color(val).hex()
                        cname = rev[old_color]
                        #cname = "_".join([name, "style", property.name.replace("-","_"), old_color.hex()[1:]])
                        #print cname
                        if cname in new_colors:
                            #print cname
                            new_color = new_colors[cname]
                            new_prop = cssutils.css.Property(name=property.name, value=new_color.hex())
                            style.setProperty(new_prop)
                            old_colors[cname] = new_color
                tag[key] = style.cssText
github AlicesReflexion / line-stickerbot / main.py View on Github external
def dl_stickers(page):
    images = page.find_all('span', attrs={"style": not ""})
    for i in images:
        imageurl = i['style']
        imageurl = cssutils.parseStyle(imageurl)
        imageurl = imageurl['background-image']
        imageurl = imageurl.replace('url(', '').replace(')', '')
        imageurl = imageurl[1:-15]
        response = urllib.request.urlopen(imageurl)
        resize_sticker(response, imageurl)
github orf / wordinserter / wordinserter / parsers / html.py View on Github external
def build_element(self, element):
        if isinstance(element, bs4.Comment):
            return None

        if isinstance(element, bs4.NavigableString):
            return Text(text=str(element))

        cls = MAPPING.get(element.name, IgnoredOperation)

        style_attr = element.attrs.get('style')
        if style_attr:
            element_style = cssutils.parseStyle(style_attr)
        else:
            element_style = None

        if cls is Image:
            if not element.attrs.get("src", None):
                cls = IgnoredOperation
            else:
                cls = partial(Image,
                              height=int(element.attrs.get("height", 0)),
                              width=int(element.attrs.get("width", 0)),
                              caption=element.attrs.get("alt", None),
                              location=element.attrs["src"])
        elif cls is HyperLink:
            if "href" not in element.attrs:
                cls = IgnoredOperation
            else:
github vinta / haul / haul / finders / pipeline / css.py View on Github external
*args, **kwargs):
    """
    Find image URL in background-image

    Example:
    <div src="http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg" class="Image iLoaded iWithTransition Frame" style="width: 100%; height: 100%; background-image: url(http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg);"></div>
    to
    http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg
    """

    now_finder_image_urls = []

    for tag in soup.find_all(style=True):
        style_string = tag['style']
        if 'background-image' in style_string.lower():
            style = cssutils.parseStyle(style_string)
            background_image = style.getProperty('background-image')
            if background_image:
                for property_value in background_image.propertyValue:
                    background_image_url = str(property_value.value)
                    if background_image_url:
                        if (background_image_url not in finder_image_urls) and \
                           (background_image_url not in now_finder_image_urls):
                            now_finder_image_urls.append(background_image_url)

    output = {}
    output['finder_image_urls'] = finder_image_urls + now_finder_image_urls

    return output
github forgeworks / quill-delta-python / delta / html.py View on Github external
def styled(element, styles):
    if element.tag != 'span':
        element = sub_element(element, 'span')
    declare = parseStyle(element.attrib.get('style', ''))
    for k, v in styles.items():
        declare.setProperty(k, v)
    element.attrib['style'] = declare.getCssText(' ')
    return element
github norbusan / calibre-debian / src / calibre / ebooks / oeb / normalize_css.py View on Github external
br = 'border-%s' % edge
                    val = tuple(parseStyle('%s: %s' % (br, raw), validate=False))[0].cssValue
                    self.assertDictEqual(border_edge_dict(expected, edge), normalizers[br](br, val))

            for raw, expected in {
                'solid 1px red': {'color':'red', 'width':'1px', 'style':'solid'},
                '1px': {'width': '1px'}, '#aaa': {'color': '#aaa'},
                'thin groove': {'width':'thin', 'style':'groove'},
            }.iteritems():
                val = tuple(parseStyle('%s: %s' % ('border', raw), validate=False))[0].cssValue
                self.assertDictEqual(border_dict(expected), normalizers['border']('border', val))

            for name, val in {
                'width': '10%', 'color': 'rgb(0, 1, 1)', 'style': 'double',
            }.iteritems():
                cval = tuple(parseStyle('border-%s: %s' % (name, val), validate=False))[0].cssValue
                self.assertDictEqual(border_val_dict(val, name), normalizers['border-'+name]('border-'+name, cval))