解析嵌入式CSS Beautifulsoup

节点

是否可以从html标记中提取嵌入的CSS属性?例如,假设我想找出“ s5”的vertical-align属性是什么。

我目前正在使用beautifulsoup,并已使用检索了span标签tag=soup.find(class_="s5")我已经尝试过了,tag.attrs["class"]但这仅给了我s5,无法将其链接到嵌入式样式。是否可以在python中做到这一点?我发现的每个此类问题都涉及解析内联CSS样式。

<html>
    <head>
        <style type="text/css">
        * {margin:0; padding:0; text-indent:0; }
        .s5 {color: #000; font-family:Verdana, sans-serif; 
             font-style: normal; font-weight: normal; 
             text-decoration: none; font-size: 17.5pt; 
             vertical-align: 10pt;}
        </style>
    </head>

    <body>
        <p class="s1" style="padding-left: 7pt; text-indent: 0pt; text-align:left;">
        This is a sample sentence. <span class="s5"> 1</span>
        </p>
    </body>
</html>

比托·本尼汉(Bitto Bennichan)

您可以使用cssutils之类的css解析器我不知道包本身是否有一个函数可以做这样的事情(有人可以对此发表评论吗?),但是我做了一个自定义函数来获取它。

from bs4 import BeautifulSoup
import cssutils
html='''
<html>
    <head>
        <style type="text/css">
        * {margin:0; padding:0; text-indent:0; }
        .s5 {color: #000; font-family:Verdana, sans-serif;
             font-style: normal; font-weight: normal;
             text-decoration: none; font-size: 17.5pt;
             vertical-align: 10pt;}
        </style>
    </head>

    <body>
        <p class="s1" style="padding-left: 7pt; text-indent: 0pt; text-align:left;">
        This is a sample sentence. <span class="s5"> 1</span>
        </p>
    </body>
</html>
'''
def get_property(class_name,property_name):
    for rule in sheet:
        if rule.selectorText=='.'+class_name:
            for property in rule.style:
                if property.name==property_name:
                    return property.value
soup=BeautifulSoup(html,'html.parser')
sheet=cssutils.parseString(soup.find('style').text)
vl=get_property('s5','vertical-align')
print(vl)

输出量

10pt

这不是完美的,但也许您可以改进它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章