python解析css文件_在Python中解析CSS

这是我降落的地方。使用了恶报的策略,用一个劈开绳子。在from bs4 import BeautifulSoup

import re

class RichText(BeautifulSoup):

"""

subclass BeautifulSoup

add behavior for generating selectors and declaration_blocks from

"""

def __init__(self, html_page):

super().__init__(html_page)

@property

def rules_as_str(self):

return str(self.style.string)

def rules(self):

split_rules = re.split('(\.c[0-9]*)', self.rules_as_str)

# side effect of split, first element is null

assert(split_rules[0] == '')

# enforce that it MUST be null, then pass over it

for i in range(1, len(split_rules), 2):

yield (split_rules[i].strip(), split_rules[i+1].strip())

if __name__ == '__main__':

with open('rich-text.html', 'r') as f:

html_file = f.read()

rich_text = RichText(html_file)

for selector, declaration_block in rich_text.rules():

print(selector)

print(declaration_block)

>>> with open("test.py") as f:

... code = compile(f.read(), "test.py", 'exec')

... exec(code)

...

.c0

{ padding: 1px 0px 0px; font-size: 11px }

.c1

{ margin: 0px; font-size: 11px }

.c2

{ font-size: 11px }

.c3

{ font-size: 11px; font-style: italic; font-weight: bold }

>>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值