我正在尝试从 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;
}
我只需要解析特定条目的“背景颜色”十六进制值,仅从“警告”到“橙色”开始。
我尝试了 urllib.request
但没有准确地工作。
如果有人可以帮助我使用 Python 脚本获取这些值,我将不胜感激。
谢谢, 艾哈迈德
最佳答案
我在您的 CSS 代码中添加了一个额外的“f”,因为它没有通过验证。
您可以使用 requests 下载文件并使用 cssutils 解析 CSS .以下代码找到所有 background-color
实例并将它们放入带有 CSS 选择器的字典中。
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'
}
关于python - 如何解析 CSS URL 中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54893442/