python如何将css文件解析为键值 [英] python how to parse css file as key value

查看:323
本文介绍了python如何将css文件解析为键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个css,如:

body, html { aaa: aaa }
h1, h2 { bbb: bbb; }
h3, h4, h5 { ccc: ccc; }

我想解析此字符串并获取有序的dict/或类似的内容:

and i want to parse this string and get an ordered dict / or something like:

{
    'body, html': 'aaa: aaa',
    'h1, h2':  'bbb: bbb;',
    'h3, h4, h5': 'ccc: ccc;'
}

我想知道所有选择器及其属性

I want to know all selectors and their properties

有人知道有什么python库可以做到这一点吗?

anybody knows any python library for accomplish this?

谢谢!

推荐答案

我建议使用 cssutils 模块.

I would suggest to use the cssutils module.

import cssutils
from pprint import pprint

css = u'''
body, html { color: blue }
h1, h2 { font-size: 1.5em; color: red}
h3, h4, h5 { font-size: small; }
'''

dct = {}
sheet = cssutils.parseString(css)

for rule in sheet:
    selector = rule.selectorText
    styles = rule.style.cssText
    dct[selector] = styles


pprint(dct)

输出:

{u'body, html': u'color: blue',
 u'h1, h2': u'font-size: 1.5em;\ncolor: red',
 u'h3, h4, h5': u'font-size: small'}

在您的问题中,您要求提供键/值表示形式.但是,如果您确实想访问单个选择器或属性,请使用rule.selectorList并对其rule.style的属性进行迭代:

In your question you asked for a key/value representation. But if you do want to access the individial selectors or proprties, use rule.selectorList and iterate over its properties for rule.style:

for property in rule.style:
    name = property.name    
    value = property.value

这篇关于python如何将css文件解析为键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆