1

I'm trying to parse some specific hex color values from a css URL (not all the contents), but don't know how to figure that out using Python.

The URL looks like the below:

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

And its contents are :

@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;
}

I just need to parse the "background-color" hex values for specific entries, starting from "warning" until "orange" ONLY.

I tries urllib.request but didn't work accurately with me.

I will be so grateful if anyone could help me get this values using a Python script.

Thanks, Ahmed

1
  • What you meant by urllib.request don't work accurately...? Requesting to URL returns the expected content? I mean CSS content. Commented Feb 26, 2019 at 20:20

1 Answer 1

2

I added an extra 'f' to your CSS code, because it didn't validate.

You can download a file using requests and parse CSS using cssutils. The following code finds all background-color instances and puts them in a dict with the CSS selector.

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)

This prints the following result:

{
  '.bg-primary': '#2ccfff',
  '.bg-success': '#8b88ff',
  '.bg-info': '#6cf',
  '.bg-warning': '#f90',
  '.bg-danger': '#7bb31a',
  '.bg-orange': '#f98e33'
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Zan for the script, appreciated. But what if I need to get specific range of values from that CSS list. for example the hex codes from "bg-warning" to "bg-orange" ONLY.
results is a dictionary, you can use standard dictionary lookup to get the values you need: bg-colour = results['.bg-orange']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.