Created
September 20, 2011 09:54
-
-
Save antonklava/1228766 to your computer and use it in GitHub Desktop.
Python class to farm Stockholms Lokaltrafik of realtime information about when busses are leaving
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib2 | |
import re | |
class SlFarm: | |
""" | |
Farms the SL website for information about the arrival times of busses | |
Only works for busses at the moment | |
Written by Anton Klava, [email protected] | |
Usage Example: | |
from SlFarm import * | |
sl = SlFarm() | |
print sl.getRealTime('gullmarsplan') | |
Tis 20 Sep 2011 11:14:35 | |
First version. Things are a bit rough. Regexp is very simple. | |
Only works for busses right now. And just a few stations. | |
Anton | |
""" | |
urls = { | |
'tussmotevagen': 'http://realtid.sl.se/?epslanguage=SV&WbSgnMdl=1860-VHVzc23DtnRldsOkZ2VuIChTdG9ja2hvbG0p-_--_-_-_', | |
'kista': 'http://realtid.sl.se/?epslanguage=SV&WbSgnMdl=9302-S2lzdGEgY2VudHJ1bSAoU3RvY2tob2xtKQ%3d%3d-_--_-_-_', | |
'gullmarsplan': 'http://realtid.sl.se/?epslanguage=SV&WbSgnMdl=9189-R3VsbG1hcnNwbGFuIChTdG9ja2hvbG0p-_--_-_-_' | |
} | |
regex = None # Regexp object | |
def __init__(self): | |
""" | |
Constructor | |
Author: Anton Klava | |
""" | |
self.regex = re.compile( | |
"<td.*?>(.+?)</td>", | |
re.IGNORECASE|re.MULTILINE|re.DOTALL | |
) | |
def cleanStr(self, str): | |
""" | |
Simple cleaning of string | |
removes tabs, newlines and carrige returns | |
Author: Anton Klava | |
""" | |
s = str | |
s = s.strip("\t\n\r") | |
return s | |
def getRealTime(self, station): | |
""" | |
Gets the realtime information for a station | |
Station must exist in self.urls. | |
Author: Anton Klava | |
""" | |
url = self.urls[station] # Get url for station | |
f = urllib2.urlopen(url) | |
page = f.read() # Get page contents | |
f.close() | |
r = self.regex.findall(page) | |
l = len(r) | |
results = [] | |
if l!=0 and l%3 == 0: | |
for i in range(l/3): | |
results.append(( | |
self.cleanStr(r[i*3 ]), | |
self.cleanStr(r[i*3+1]), | |
self.cleanStr(r[i*3+2]) | |
)) | |
return results | |
else: | |
raise Exception( | |
"Failed to get realtime results from SL. "+ | |
"Station: " + station + | |
"Url: " + url | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment