Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Python to fetch Republican Primary results in JSON

DZone's Guide to

Using Python to fetch Republican Primary results in JSON

· Web Dev Zone ·
Free Resource

Classify programming languages: Build a model that predicts a code's programming language based on its text.  Content provided by IBM Developer. 

Over at Pastie.org, they have an interesting Python Script that returns the results of the Republican Primary in JSON.
import json
import sys
import urllib2
from BeautifulSoup import BeautifulSoup
import re


#Usage python elections.py State Name
#Example python elections.py massachusetts

state = sys.argv[1]
url = ("http://elections.msnbc.msn.com/ns/politics/2012/%s/Republican/primary/" % state)
html = BeautifulSoup(urllib2.urlopen(url)).prettify()

soup = BeautifulSoup(html)


cities = soup.findAll("div", {"class": re.compile(r'\bresultSlice\ countyResults\b')})

results = {}

for city in cities:
    cityName = ''.join((city.find("div", {"class": "state"})).findAll(text=True)).strip()
    results.setdefault(cityName, {})

    table = city.findAll("table", {"class": "results"})
    for rows in table:
        rows = rows.findAll("tr", {"class": re.compile(r'\brep\b')})
        for row in rows:
            try:
                canidate    = ''.join(row.find("td", {"class": "name"}).findAll(text=True)).strip()
                votes       = ''.join(row.find("td", {"class": "votes"}).findAll(text=True)).strip()
                if votes == "":
                    votes = 0
                results.setdefault(cityName, {}).setdefault((canidate.replace("\n","")).replace("                            ", " "), {})['votes'] = votes
            except Exception:
                continue

print json.dumps(results, indent=4)

Enjoy!

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}