BeautifulSoup:从HTML获取CSS类
有没有一种方法可以从HTML文件中获取CSS类BeautifulSoup
?示例片段:
<style type="text/css">
p.c3 {text-align: justify}
p.c2 {text-align: left}
p.c1 {text-align: center}
</style>
完美的输出将是:
cssdict = {
'p.c3': {'text-align': 'justify'},
'p.c2': {'text-align': 'left'},
'p.c1': {'text-align': 'center'}
}
尽管这样可以:
L = [
('p.c3', {'text-align': 'justify'}),
('p.c2', {'text-align': 'left'}),
('p.c1', {'text-align': 'center'})
]
-
BeautifulSoup本身根本不解析CSS样式声明,但是您 可以 提取这些部分,然后使用专用的CSS解析器对其进行解析。
根据您的需求,有多个CSS解析器可用于python。我会选择cssutils(需要python
2.5或更高版本(包括python 3)),它在支持方面是最完整的,并且也支持内联样式。抓取并解析所有样式部分(例如cssutils的示例):
import cssutils sheets = [] for styletag in tree.findAll('style', type='text/css') if not styletag.string: # probably an external sheet continue sheets.append(cssutils.parseStyle(styletag.string))
随着
cssutil
然后你可以结合这些,进口的决心,甚至把它取外部样式表。