Code to scape CNN.com election results

My election party tomorrow will feature DMX controlled RGB LED lighting.  The color of the house should reflect the electoral balance.  The color will start purple, and drift toward either red or blue, depending on who’s winning.

We are hoping that as the night wears on, the room will turn more and more BLUE.

In order to do this, it was necessary to obtain live election results.  Presented for your use is a simple python urllib2 scraper which will fetch live results from CNN.com.

Return value is ((dpopular, delectoral), (rpopular, relectoral)).  Furthermore, when CNN calls the race, the get method throws an ElectionWon exception.

This code is in the public domain. The data, however, actually costs around $4000 if you buy it directly from exit-poll.net, the clearinghouse for aggregated exit poll data. Yikes!

UPDATED:
I’ve updated the code with a function that will normalize the results to -1 => democrat wins, 1 => republican wins. The function takes an interval argument which constrains the range over which the function is computed. That is to say, for interval == 0.25 this function returns -1.0 if Obama is winning by 25%.

I’m normalizing this from (republican_votes)/(democratic_votes+republican_votes). So it doesn’t matter what the format of that vote value is scaled to.


file: cnn.py

import urllib2
import re

class ElectionWon(Exception):
  pass

class CNN(object):
  def __init__(self):
    self.url = "http://www.cnn.com/ELECTION/2008/results/president/"

  def get(self):
    """return the electoral balance
        (dpopular, delectoral), (rpopular, relectoral)
    """
    u = urllib2.urlopen(self.url)
    for line in u.readlines():
      res = re.search(r'var CNN_NData=(.*?);', line)
      if res is not None:
        data = res.group(1)
        data = data.replace("true", "True")
        data = data.replace("false", "False")
        data = eval(data)

        d,r = None, None
        for candidate in data['P']['candidates']:
          if candidate['party'] == 'D':
            d = candidate['votes'], candidate['evotes']
            if candidate['winner']:
              raise ElectionWon("D")
          elif candidate['party'] == 'R':
            r = candidate['votes'], candidate['evotes']
            if candidate['winner']:
              raise ElectionWon("R")

    return d,r

def normalize(d,r, interval=0.5):
  """normalize to
    -1 => democrat winning
    +1 => republican winning
    abs(1.0) is having "2*interval" higher percent than the other guy
  """
  if d+r == 0: return 0.0
  rnorm = 2.0*(1.0*r/(d+r) - 0.5) / (2*interval)
  if rnorm > 1.0: rnorm = 1.0
  if rnorm < -1.0: rnorm = -1.0
  return rnorm

if __name__=='__main__':
  cnn = CNN()
  print cnn.get()

Comments are closed.

You never know who the next overlords will be. I’m hedging my bets.