Saturday, October 25, 2014

Tips: Python: Calculate Contrast Ratio of html text using Python and Selenium

from __future__ import division
from selenium import webdriver
from selenium.webdriver.common.by import By
import re


def calculate_luminance(r, g, b):
    RsRGB = r/255
    GsRGB = g/255
    BsRGB = b/255
    R = (RsRGB/12.92) if (RsRGB <= 0.03928) else (((RsRGB + 0.055)/1.055)**2.4)
    G = (GsRGB/12.92) if (GsRGB <= 0.03928) else (((GsRGB + 0.055)/1.055)**2.4)
    B = (BsRGB/12.92) if (BsRGB <= 0.03928) else (((BsRGB + 0.055)/1.055)**2.4)
    return (0.2126 * R + 0.7152 * G + 0.0722 * B)


def getcolor(colorcode):
    """
    provide the colorcode in rgba format
    """
    return re.compile("rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d+)\)",
        re.IGNORECASE).findall(colorcode)[0]


def max(l1, l2):
    return l1 if l1 >=l2 else l2


def min(l1, l2):
    return l2 if l1 >=l2 else l1


def get_contrast_ratio(front_col, backend_color):
    bkg_colors = getcolor(backend_color)
    l1 = calculate_luminance(int(bkg_colors[0]),
        int(bkg_colors[1]), int(bkg_colors[2]))
    frd_colors = getcolor(front_col)
    l2 = calculate_luminance(int(frd_colors[0]),
                             int(frd_colors[1]), 
                             int(frd_colors[2]))
    return(round((max(L1, L2) + 0.05)/(min(L1, L2) + 0.05)*10)/10)


if __name__ == "__main__":
    #for testing and how to use itonly
    url = 'http://www.w3.org/Talks/2012/0416-CSS-WWW2012/Demos/transitions/demo-transitions-1.html#no_transition'
    driver = webdriver.Firefox()
    driver.implicitly_wait(30)
    driver.get(url)
    we1 = driver.find_element(By.XPATH, "//li[@id='no_transition']")
    print get_contrast_ratio(we1.value_of_css_property("color"),
                             we1.value_of_css_property("background-color"))

No comments: