Skip to content

Instantly share code, notes, and snippets.

@craigderington
Last active September 26, 2016 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigderington/e5385b7ce339a0a7ef63fb2989a280ff to your computer and use it in GitHub Desktop.
Save craigderington/e5385b7ce339a0a7ef63fb2989a280ff to your computer and use it in GitHub Desktop.
CTA bus route tracking from Python Data Hacking
#! /usr/bin/python
import time
import requests
import xml.etree.ElementTree as ET
my_latitude = 39.0548746
url = 'http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route='
route = str(input('Please select a bus route to view: '))
hdr = {
'user-agent': 'superman G2'
}
print('Querying the Chicago Transit Authority for bus route ' + route + '.')
try:
r = requests.get(url + route, headers=hdr)
if r.status_code == 200:
data = r.text
with open('data/routes/cta-bus-route' + route.strip() + '.xml', 'w') as f:
f.write(data)
except ConnectionError as e:
print('The route could not be found.' + e)
doc = ET.parse('data/routes/cta-bus-route' + route.strip() + '.xml')
time.sleep(3)
if doc.findall('error'):
print('Invalid route request.')
else:
print('The following buses for route ' + route.strip() + ' are currently in transit...')
for bus in doc.findall('bus'):
lat = float(bus.findtext('lat'))
if lat >= my_latitude:
bus_id = bus.findtext('id')
bus_dir = bus.findtext('d')
bus_fs = bus.findtext('fs')
if bus_dir.startswith('North'):
print('Northbound ' + bus_id + ' @ ' + bus_fs + ' near: ' + str(lat))
elif bus_dir.startswith('West'):
print('Westbound ' + bus_id + ' @ ' + bus_fs + ' near: ' + str(lat))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment