开发者社区> 问答> 正文

解析嵌入式css beautifulsoup

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

我目前正在使用beautifulsoup并检索了span-tag tag=soup.find(class_="s5")。我试过tag.attrs["class"]但是这只是给了我s5,没有办法将它链接到嵌入式样式。是否可以在python中执行此操作?我发现的这类问题涉及解析内联css样式。

<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>

展开
收起
一码平川MACHEL 2019-01-23 10:51:26 1812 0
1 条回答
写回答
取消 提交回答
  • 你可以使用像cssutils这样的css解析器。我不知道包中是否有一个函数来执行这样的操作(有人可以对此进行评论吗?),但我做了一个自定义函数来获取它。

    from bs4 import BeautifulSoup
    import cssutils
    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>


    '''
    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
    这并不完美,但也许你可以改进它。

    2019-07-17 23:26:33
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
阿里云HBase产品体系架构及特性解析 立即下载
ECS块存储产品全面解析 立即下载
神龙云服务器产品及技术深度解析 立即下载

相关镜像