如何解析CSS URL中的特定值

2024-10-04 05:31:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从css URL解析一些特定的十六进制颜色值(不是所有的内容),但不知道如何使用Python来解决这个问题。你知道吗

URL如下所示:

https://abcdomain.com/styles/theme.css

其内容包括:

@charset "UTF-8"; /* CSS Document */ .bg-primary { background-color: #2ccfff; color: white; } .bg-success { background-color: #8b88ff; color: white; } .bg-info { background-color: #66ccff; color: white; } .bg-warning { background-color: #ff9900; color: white; } .bg-danger { background-color: #7bb31a; color: white; } .bg-orange { background-color: #f98e33; color: white; }

我只需要解析特定条目的“background color”十六进制值,从“warning”到“orange”。你知道吗

我试过urllib.request,但没有准确地与我合作。你知道吗

如果有人能帮助我使用Python脚本获得这些值,我将非常感激。你知道吗

谢谢你, 艾哈迈德


Tags: httpscomurl内容颜色themecsscolor
1条回答
网友
1楼 · 发布于 2024-10-04 05:31:29

我在CSS代码中添加了一个额外的“f”,因为它没有验证。你知道吗

您可以使用requests下载文件,并使用cssutils解析CSS。下面的代码查找所有background-color实例,并使用CSS选择器将它们放入dict中。你知道吗

import requests
import cssutils

# Use this instead of requests if you want to read from a local file
# css = open('test.css').read()

url = 'https://abcdomain.com/styles/theme.css'
r = requests.get(url)
css = r.content

sheet = cssutils.parseString(css)

results = {}
for rule in sheet:
    if rule.type == rule.STYLE_RULE:
        for prop in rule.style:
            if prop.name == 'background-color':
                results[rule.selectorText] = prop.value

print(results)

这将打印以下结果:

{
  '.bg-primary': '#2ccfff',
  '.bg-success': '#8b88ff',
  '.bg-info': '#6cf',
  '.bg-warning': '#f90',
  '.bg-danger': '#7bb31a',
  '.bg-orange': '#f98e33'
}

相关问题 更多 >