我有一个像这样的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 库可以实现这个吗?
thanks!
我建议使用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)
Output:
{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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)