BeautifulSoup:从 html 获取 css 类 [英] BeautifulSoup: get css classes from html

查看:16
本文介绍了BeautifulSoup:从 html 获取 css 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 BeautifulSoup 从 HTML 文件中获取 CSS 类?示例片段:

Is there a way to get CSS classes from an HTML file using BeautifulSoup? Example snippet:

<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 解析器解析它们.

BeautifulSoup itself doesn't parse CSS style declarations at all, but you can extract such sections then parse them with a dedicated CSS parser.

根据您的需要,python 提供了多种 CSS 解析器;我会选择 cssutils(需要 python 2.5 或更高版本(包括 python 3)),它的支持最完整,并且支持内联样式也是如此.

Depending on your needs, there are several CSS parsers available for python; I'd pick cssutils (requires python 2.5 or up (including python 3)), it is the most complete in it's support, and supports inline styles too.

其他选项是 css-pytinycss.

抓取并解析所有样式部分(以 cssutils 为例):

To grab and parse such all style sections (example with 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,您可以组合这些,解析导入,甚至获取外部样式表.

With cssutil you can then combine these, resolve imports, and even have it fetch external stylesheets.

这篇关于BeautifulSoup:从 html 获取 css 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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