本文整理汇总了Python中cssutils.CSSParser.parseStyle方法的典型用法代码示例。如果您正苦于以下问题:Python CSSParser.parseStyle方法的具体用法?Python CSSParser.parseStyle怎么用?Python CSSParser.parseStyle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cssutils.CSSParser
的用法示例。
在下文中一共展示了CSSParser.parseStyle方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: normalize_filter_css
# 需要导入模块: from cssutils import CSSParser [as 别名]
# 或者: from cssutils.CSSParser import parseStyle [as 别名]
def normalize_filter_css(props):
import logging
ans = set()
p = CSSParser(loglevel=logging.CRITICAL, validate=False)
for prop in props:
n = normalizers.get(prop, None)
ans.add(prop)
if n is not None and prop in SHORTHAND_DEFAULTS:
dec = p.parseStyle('%s: %s' % (prop, SHORTHAND_DEFAULTS[prop]))
cssvalue = dec.getPropertyCSSValue(dec.item(0))
ans |= set(n(prop, cssvalue))
return ans
示例2: parse_css
# 需要导入模块: from cssutils import CSSParser [as 别名]
# 或者: from cssutils.CSSParser import parseStyle [as 别名]
def parse_css(self, data, fname='<string>', is_declaration=False):
from cssutils import CSSParser, log
log.setLevel(logging.WARN)
log.raiseExceptions = False
if isinstance(data, bytes):
data = self.decode(data)
if not self.tweak_mode:
data = self.css_preprocessor(data)
parser = CSSParser(loglevel=logging.WARNING,
# We dont care about @import rules
fetcher=lambda x: (None, None), log=_css_logger)
if is_declaration:
data = parser.parseStyle(data, validate=False)
else:
data = parser.parseString(data, href=fname, validate=False)
return data
示例3: parse_css
# 需要导入模块: from cssutils import CSSParser [as 别名]
# 或者: from cssutils.CSSParser import parseStyle [as 别名]
def parse_css(data, fname='<string>', is_declaration=False, decode=None, log_level=None, css_preprocessor=None):
if log_level is None:
import logging
log_level = logging.WARNING
from cssutils import CSSParser, log
from calibre.ebooks.oeb.base import _css_logger
log.setLevel(log_level)
log.raiseExceptions = False
if isinstance(data, bytes):
data = data.decode('utf-8') if decode is None else decode(data)
if css_preprocessor is not None:
data = css_preprocessor(data)
parser = CSSParser(loglevel=log_level,
# We dont care about @import rules
fetcher=lambda x: (None, None), log=_css_logger)
if is_declaration:
data = parser.parseStyle(data, validate=False)
else:
data = parser.parseString(data, href=fname, validate=False)
return data
示例4: StatsCollector
# 需要导入模块: from cssutils import CSSParser [as 别名]
# 或者: from cssutils.CSSParser import parseStyle [as 别名]
class StatsCollector(object):
def __init__(self, container, do_embed=False):
self.container = container
self.log = self.logger = container.log
self.do_embed = do_embed
must_use_qt()
self.parser = CSSParser(loglevel=logging.CRITICAL, log=logging.getLogger('calibre.css'))
self.first_letter_pat = regex.compile(r'^[\p{Ps}\p{Ps}\p{Pe}\p{Pi}\p{Pf}\p{Po}]+', regex.VERSION1 | regex.UNICODE)
self.loop = QEventLoop()
self.view = QWebView()
self.page = Page(self.log)
self.view.setPage(self.page)
self.page.setViewportSize(QSize(1200, 1600))
self.view.loadFinished.connect(self.collect,
type=Qt.QueuedConnection)
self.render_queue = list(container.spine_items)
self.font_stats = {}
self.font_usage_map = {}
self.font_spec_map = {}
self.font_rule_map = {}
self.all_font_rules = {}
QTimer.singleShot(0, self.render_book)
if self.loop.exec_() == 1:
raise Exception('Failed to gather statistics from book, see log for details')
def log_exception(self, *args):
orig = self.log.filter_level
try:
self.log.filter_level = self.log.DEBUG
self.log.exception(*args)
finally:
self.log.filter_level = orig
def render_book(self):
try:
if not self.render_queue:
self.loop.exit()
else:
self.render_next()
except:
self.log_exception('Rendering failed')
self.loop.exit(1)
def render_next(self):
item = unicode(self.render_queue.pop(0))
self.current_item = item
load_html(item, self.view)
def collect(self, ok):
if not ok:
self.log.error('Failed to render document: %s'%self.container.relpath(self.current_item))
self.loop.exit(1)
return
try:
self.page.load_js()
self.collect_font_stats()
except:
self.log_exception('Failed to collect font stats from: %s'%self.container.relpath(self.current_item))
self.loop.exit(1)
return
self.render_book()
def href_to_name(self, href, warn_name):
if not href.startswith('file://'):
self.log.warn('Non-local URI in', warn_name, ':', href, 'ignoring')
return None
src = href[len('file://'):]
if iswindows and len(src) > 2 and (src[0], src[2]) == ('/', ':'):
src = src[1:]
src = src.replace('/', os.sep)
src = unquote(src)
name = self.container.abspath_to_name(src)
if not self.container.has_name(name):
self.log.warn('Missing resource', href, 'in', warn_name,
'ignoring')
return None
return name
def collect_font_stats(self):
self.page.evaljs('window.font_stats.get_font_face_rules()')
font_face_rules = self.page.bridge_value
if not isinstance(font_face_rules, list):
raise Exception('Unknown error occurred while reading font-face rules')
# Weed out invalid font-face rules
rules = []
import tinycss
parser = tinycss.make_full_parser()
for rule in font_face_rules:
ff = rule.get('font-family', None)
if not ff:
continue
style = self.parser.parseStyle('font-family:%s'%ff, validate=False)
#.........这里部分代码省略.........
示例5: StatsCollector
# 需要导入模块: from cssutils import CSSParser [as 别名]
# 或者: from cssutils.CSSParser import parseStyle [as 别名]
class StatsCollector(object):
def __init__(self, container, do_embed=False):
self.container = container
self.log = self.logger = container.log
self.do_embed = do_embed
must_use_qt()
self.parser = CSSParser(loglevel=logging.CRITICAL, log=logging.getLogger('calibre.css'))
self.loop = QEventLoop()
self.view = QWebView()
self.page = Page(self.log)
self.view.setPage(self.page)
self.page.setViewportSize(QSize(1200, 1600))
self.view.loadFinished.connect(self.collect,
type=Qt.QueuedConnection)
self.render_queue = list(container.spine_items)
self.font_stats = {}
self.font_usage_map = {}
self.font_spec_map = {}
self.font_rule_map = {}
self.all_font_rules = {}
QTimer.singleShot(0, self.render_book)
if self.loop.exec_() == 1:
raise Exception('Failed to gather statistics from book, see log for details')
def render_book(self):
try:
if not self.render_queue:
self.loop.exit()
else:
self.render_next()
except:
self.logger.exception('Rendering failed')
self.loop.exit(1)
def render_next(self):
item = unicode(self.render_queue.pop(0))
self.current_item = item
load_html(item, self.view)
def collect(self, ok):
if not ok:
self.log.error('Failed to render document: %s'%self.container.relpath(self.current_item))
self.loop.exit(1)
return
try:
self.page.load_js()
self.collect_font_stats()
except:
self.log.exception('Failed to collect font stats from: %s'%self.container.relpath(self.current_item))
self.loop.exit(1)
return
self.render_book()
def href_to_name(self, href, warn_name):
if not href.startswith('file://'):
self.log.warn('Non-local URI in', warn_name, ':', href, 'ignoring')
return None
src = href[len('file://'):]
if iswindows and len(src) > 2 and (src[0], src[2]) == ('/', ':'):
src = src[1:]
src = src.replace('/', os.sep)
src = unquote(src)
name = self.container.abspath_to_name(src)
if not self.container.has_name(name):
self.log.warn('Missing resource', href, 'in', warn_name,
'ignoring')
return None
return name
def collect_font_stats(self):
self.page.evaljs('window.font_stats.get_font_face_rules()')
font_face_rules = self.page.bridge_value
if not isinstance(font_face_rules, list):
raise Exception('Unknown error occurred while reading font-face rules')
# Weed out invalid font-face rules
rules = []
for rule in font_face_rules:
ff = rule.get('font-family', None)
if not ff:
continue
style = self.parser.parseStyle('font-family:%s'%ff, validate=False)
ff = [x.value for x in
style.getProperty('font-family').propertyValue]
if not ff or ff[0] == 'inherit':
continue
rule['font-family'] = frozenset(icu_lower(f) for f in ff)
src = rule.get('src', None)
if not src:
continue
if src.startswith('url(') and src.endswith(')') and src[4] not in {'"', "'"}:
# Quote the url otherwise cssutils fails to parse it if it has
# ' or " in it
#.........这里部分代码省略.........
示例6: StatsCollector
# 需要导入模块: from cssutils import CSSParser [as 别名]
# 或者: from cssutils.CSSParser import parseStyle [as 别名]
class StatsCollector(object):
def __init__(self, container, do_embed=False):
self.container = container
self.log = self.logger = container.log
self.do_embed = do_embed
must_use_qt()
self.parser = CSSParser(loglevel=logging.CRITICAL, log=logging.getLogger("calibre.css"))
self.loop = QEventLoop()
self.view = QWebView()
self.page = Page(self.log)
self.view.setPage(self.page)
self.page.setViewportSize(QSize(1200, 1600))
self.view.loadFinished.connect(self.collect, type=Qt.QueuedConnection)
self.render_queue = list(container.spine_items)
self.font_stats = {}
self.font_usage_map = {}
self.font_spec_map = {}
self.font_rule_map = {}
self.all_font_rules = {}
QTimer.singleShot(0, self.render_book)
if self.loop.exec_() == 1:
raise Exception("Failed to gather statistics from book, see log for details")
def render_book(self):
try:
if not self.render_queue:
self.loop.exit()
else:
self.render_next()
except:
self.logger.exception("Rendering failed")
self.loop.exit(1)
def render_next(self):
item = unicode(self.render_queue.pop(0))
self.current_item = item
load_html(item, self.view)
def collect(self, ok):
if not ok:
self.log.error("Failed to render document: %s" % self.container.relpath(self.current_item))
self.loop.exit(1)
return
try:
self.page.load_js()
self.collect_font_stats()
except:
self.log.exception("Failed to collect font stats from: %s" % self.container.relpath(self.current_item))
self.loop.exit(1)
return
self.render_book()
def href_to_name(self, href, warn_name):
if not href.startswith("file://"):
self.log.warn("Non-local URI in", warn_name, ":", href, "ignoring")
return None
src = href[len("file://") :]
if iswindows and len(src) > 2 and (src[0], src[2]) == ("/", ":"):
src = src[1:]
src = src.replace("/", os.sep)
src = unquote(src)
name = self.container.abspath_to_name(src)
if not self.container.has_name(name):
self.log.warn("Missing resource", href, "in", warn_name, "ignoring")
return None
return name
def collect_font_stats(self):
self.page.evaljs("window.font_stats.get_font_face_rules()")
font_face_rules = self.page.bridge_value
if not isinstance(font_face_rules, list):
raise Exception("Unknown error occurred while reading font-face rules")
# Weed out invalid font-face rules
rules = []
for rule in font_face_rules:
ff = rule.get("font-family", None)
if not ff:
continue
style = self.parser.parseStyle("font-family:%s" % ff, validate=False)
ff = [x.value for x in style.getProperty("font-family").propertyValue]
if not ff or ff[0] == "inherit":
continue
rule["font-family"] = frozenset(icu_lower(f) for f in ff)
src = rule.get("src", None)
if not src:
continue
style = self.parser.parseStyle("background-image:%s" % src, validate=False)
src = style.getProperty("background-image").propertyValue[0].uri
name = self.href_to_name(src, "@font-face rule")
if name is None:
continue
rule["src"] = name
normalize_font_properties(rule)
#.........这里部分代码省略.........