2 # -*- coding: UTF-8 -*-
4 from BeautifulSoup import BeautifulSoup, NavigableString
5 from urllib2 import urlopen
6 from urllib import urlencode
8 from datetime import datetime, time
9 from textwrap import wrap
14 POSITION_TYPES = ('stop', 'address', 'poi')
16 DEBUGLOG = os.path.expanduser('~/gotoVienna.debug')
18 class ParserError(Exception):
20 def __init__(self, msg='Parser error'):
24 UNKNOWN, CORRECTION, RESULT = range(3)
27 def search(origin_tuple, destination_tuple, dtime=None):
28 """ build route request
29 returns html result (as urllib response)
32 dtime = datetime.now()
34 origin, origin_type = origin_tuple
35 destination, destination_type = destination_tuple
36 if not origin_type in POSITION_TYPES or\
37 not destination_type in POSITION_TYPES:
38 raise ParserError('Invalid position type')
40 post = settings.search_post
41 post['name_origin'] = origin
42 post['type_origin'] = origin_type
43 post['name_destination'] = destination
44 post['type_destination'] = destination_type
45 post['itdDateDayMonthYear'] = dtime.strftime('%d.%m.%Y')
46 post['itdTime'] = dtime.strftime('%H:%M')
47 params = urlencode(post)
48 url = '%s?%s' % (settings.action, params)
51 f = open(DEBUGLOG, 'a')
55 print 'Unable to write to DEBUGLOG: %s' % DEBUGLOG
61 """ Parser for search response
64 def __init__(self, html):
65 self.soup = BeautifulSoup(html)
68 if self.soup.find('form', {'id': 'form_efaresults'}):
69 return PageType.RESULT
71 if self.soup.find('div', {'class':'form_error'}):
72 return PageType.CORRECTION
74 return PageType.UNKNOWN
76 def get_correction(self):
77 nlo = self.soup.find('select', {'id': 'nameList_origin'})
78 nld = self.soup.find('select', {'id': 'nameList_destination'})
80 if not nlo and not nld:
81 raise ParserError('Unable to parse html')
84 origin = map(lambda x: x.text, nlo.findAll('option'))
88 destination = map(lambda x: x.text, nld.findAll('option'))
92 return (origin, destination)
95 return rParser(str(self.soup))
100 """ Parser for routing results
103 def __init__(self, html):
104 self.soup = BeautifulSoup(html)
105 self._overview = None
109 def get_tdtext(cls, x, cl):
110 return x.find('td', {'class': cl}).text
113 def get_change(cls, x):
114 y = rParser.get_tdtext(x, 'col_change')
121 def get_price(cls, x):
122 y = rParser.get_tdtext(x, 'col_price')
124 return float(y.replace(',', '.'))
129 def get_date(cls, x):
130 y = rParser.get_tdtext(x, 'col_date')
132 return datetime.strptime(y, '%d.%m.%Y').date()
137 def get_time(cls, x):
138 y = rParser.get_tdtext(x, 'col_time')
140 if (y.find("-") > 0):
141 return map(lambda z: time(*map(int, z.split(':'))), y.split('-'))
143 return map(lambda z: time(*map(int, z.split(':'))), wrap(y, 5))
148 def get_duration(cls, x):
149 y = rParser.get_tdtext(x, 'col_duration')
151 return time(*map(int, y.split(":")))
156 for detail in self.details():
159 def _parse_details(self):
160 tours = self.soup.findAll('div', {'class': 'data_table tourdetail'})
162 trips = map(lambda x: map(lambda y: {
163 'time': rParser.get_time(y),
164 'station': map(lambda z: z[2:].strip(),
165 filter(lambda x: type(x) == NavigableString, y.find('td', {'class': 'col_station'}).contents)), # filter non NaviStrings
166 'info': map(lambda x: x.strip(),
167 filter(lambda z: type(z) == NavigableString, y.find('td', {'class': 'col_info'}).contents)),
168 }, x.find('tbody').findAll('tr')),
174 """returns list of trip details
175 [ [ { 'time': [datetime.time, datetime.time] if time else [],
176 'station': [u'start', u'end'] if station else [],
177 'info': [u'start station' if station else u'details for walking', u'end station' if station else u'walking duration']
178 }, ... # next trip step
179 ], ... # next trip possibility
182 if not self._details:
183 self._details = self._parse_details()
187 def _parse_overview(self):
190 table = self.soup.find('table', {'id': 'tbl_fahrten'})
192 # check if there is an overview table
193 if table and table.findAll('tr'):
195 rows = table.findAll('tr')[1:] # cut off headline
197 overview = map(lambda x: {
198 'date': rParser.get_date(x),
199 'time': rParser.get_time(x),
200 'duration': rParser.get_duration(x), # grab duration
201 'change': rParser.get_change(x),
202 'price': rParser.get_price(x),
206 raise ParserError('Unable to parse overview')
219 if not self._overview:
221 self._overview = self._parse_overview()
222 except AttributeError:
223 f = open(DEBUGLOG, 'w')
224 f.write(str(self.soup))
227 return self._overview
229 if __name__ == '__main__':
230 parser = argparse.ArgumentParser(description='Get public transport route for Vienna')
231 parser.add_argument('-o', metavar='name', type=str, help='origin', required=True)
232 parser.add_argument('-d', metavar='name', type=str, help='destination', required=True)
233 parser.add_argument('-ot', metavar='type', type=str, help='origin type: %s' % ' | '.join(POSITION_TYPES), default='stop', choices=POSITION_TYPES)
234 parser.add_argument('-dt', metavar='type', type=str, help='destination type: %s' % ' | '.join(POSITION_TYPES), default='stop', choices=POSITION_TYPES)
236 args = parser.parse_args()
237 html = search((args.o, args.ot), (args.d, args.dt)).read()
239 parser = sParser(html)
240 state = parser.check_page()
242 if state == PageType.CORRECTION:
244 cor = parser.get_correction()
247 print '* Origin ambiguous:'
249 while not lo or not lo.isdigit() or int(lo) > len(cor[0]):
252 print '%d. %s' % (i, c)
254 lo = sys.stdin.readline().strip()
256 args.o = cor[0][int(lo) - 1]
260 print '* Destination ambiguous:'
262 while not ld or not ld.isdigit() or int(ld) > len(cor[1]):
265 print '%d. %s' % (j, c)
267 ld = sys.stdin.readline().strip()
269 args.d = cor[1][int(ld) - 1]
271 html = search((args.o.encode('UTF-8'), args.ot), (args.d.encode('UTF-8'), args.dt)).read()
273 parser = sParser(html)
274 state = parser.check_page()
277 print 'PANIC at correction page'
279 if state == PageType.RESULT:
280 parser = rParser(html)
282 overviews = parser.overview
283 details = parser.details
286 for r in range(len(overviews)):
287 print '%d. [%s] %s-%s (%s)' % (r + 1, overviews[r]['date'], overviews[r]['time'][0], overviews[r]['time'][1], overviews[r]['duration'])
289 l = sys.stdin.readline().strip()
293 if l.isdigit() and int(l) <= len(details):
294 for detail in details[int(l) - 1]:
295 if detail['time'] and detail['station']:
296 time = '%s - %s' % (detail['time'][0].strftime(TIMEFORMAT), detail['time'][1].strftime(TIMEFORMAT))
297 print '[%s] %s\n%s' % (time, ' -> '.join(detail['station']), '\n'.join(detail['info']))
299 print '\n'.join(detail['info'])
306 elif state == PageType.UNKNOWN:
307 print 'PANIC unknown result'