Created
January 7, 2010 11:21
-
-
Save edwardgeorge/271172 to your computer and use it in GitHub Desktop.
identify unused css selectors in a page, proof of concept
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""identify unused css selectors.""" | |
from functools import partial | |
import re | |
import sys | |
import urlparse | |
import cssutils | |
from lxml import cssselect | |
from lxml import html | |
remove_pseudo = partial(re.compile(r':(hover|link|visited|active)').sub, '') | |
def process(url): | |
tree = html.parse(url) | |
sheets = tree.xpath('//link[@rel="stylesheet"]/@href') | |
for sheet in sheets: | |
cssurl = urlparse.urljoin(url, sheet) | |
process_stylesheet(tree, cssurl) | |
def process_stylesheet(doc, cssurl): | |
print cssurl | |
ss = cssutils.parseUrl(cssurl) | |
rules = (rule for rule in ss if rule.type == rule.STYLE_RULE) | |
for rule in rules: | |
key = rule.selectorText | |
count = match_rule(doc, rule) | |
if not count: | |
print ' -', key | |
def match_rule(doc, rule): | |
selectors = (selector for selector in rule.selectorList) | |
selectors = (remove_pseudo(s.selectorText) for s in selectors) | |
selectors = (cssselect.CSSSelector(s) for s in selectors) | |
return sum(len(s.evaluate(doc)) for s in selectors) | |
if __name__ == '__main__': | |
process(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment