Skip to content

Instantly share code, notes, and snippets.

@edwardgeorge
Created January 7, 2010 11:21
Show Gist options
  • Save edwardgeorge/271172 to your computer and use it in GitHub Desktop.
Save edwardgeorge/271172 to your computer and use it in GitHub Desktop.
identify unused css selectors in a page, proof of concept
#!/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