解析嵌入式CSS(BeautifulSoup)

4

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

我目前正在使用beautifulsoup,并使用tag=soup.find(class_="s5")检索了span标签。我尝试过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>


你有没有研究过tinycss - chitown88
我在文档中找不到任何与此相关的内容。 - nodel
2个回答

4
你可以使用类似 [cssutils][1] 的 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

这并不完美,但或许你可以进一步改进它。 [1]: https://pypi.org/project/cssutils/


4
为了改进 cssutils answer 的内容:
对于内联的 style="..." 标签:
import cssutils

# get the style from beautiful soup, like: 
# style = tag['style']
style = "color: hotpink; background-color:#ff0000; visibility:hidden"

parsed_style = cssutils.parseStyle(style)

现在您可以像使用字典一样使用parsed_style
print(parsed_style['color'])  # hotpink
print(parsed_style['background-color'])  # f00
print(parsed_style['visibility'])  # hidden


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接