【问题标题】:parse embedded css beautifulsoup解析嵌入的 css beautifulsoup
【发布时间】:2019-06-16 08:42:09
【问题描述】:

是否可以从 html 标签中提取嵌入的 css 属性?例如,假设我想找出“s5”的垂直对齐属性是什么。

我目前正在使用 beautifulsoup,并已检索到带有 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>

【问题讨论】:

  • 你看过tinycss吗?
  • 我在文档中找不到与此相关的任何内容

标签: python html css beautifulsoup


【解决方案1】:

改进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)

现在像使用dict 一样使用parsed_style

print(parsed_style['color'])  # hotpink
print(parsed_style['background-color'])  # f00
print(parsed_style['visibility'])  # hidden


【讨论】:

    【解决方案2】:

    您可以使用 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
    

    这并不完美,但也许你可以改进它。

    【讨论】:

      猜你喜欢
      • 2017-07-24
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      • 2015-01-27
      • 2016-09-23
      • 2017-02-12
      • 1970-01-01
      相关资源
      最近更新 更多