python如何解析css文件作为键值

时间:2014-02-09 13:41:18

标签: python css parsing

我有一个像css一样的CSS:

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

我希望解析这个字符串并得到一个有序的字典/或类似的东西:

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

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

任何人都知道有任何python库可以实现这个目标吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

我建议使用cssutils模块。

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的属性:

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

答案 1 :(得分:-1)

试试这个

>>> a = [css for css in text.split("}\n") if css]
>>> a
['body, html { aaa: aaa ', 'h1, h2 { bbb: bbb; ', 'h3, h4, h5 { ccc: ccc; ']
>>> {i.split("{")[0].strip():i.split("{")[1].strip() for i in a}
{'h3, h4, h5': 'ccc: ccc;', 'body, html': 'aaa: aaa', 'h1, h2': 'bbb: bbb;'}

如果你想摆脱;只是strip

相关问题