1 from BeautifulSoup import BeautifulSoup, NavigableString
2 from urllib2 import urlopen
3 from urllib import urlencode
5 from datetime import datetime, time
6 from textwrap import wrap
10 POSITION_TYPES = ('stop', 'address', 'poi')
13 class ParserError(Exception):
15 def __init__(self, msg='Parser error'):
19 UNKNOWN, CORRECTION, RESULT = range(3)
22 def search(origin_tuple, destination_tuple, dtime=None):
23 """ build route request
24 returns html result (as urllib response)
27 dtime = datetime.now()
29 origin, origin_type = origin_tuple
30 destination, destination_type = destination_tuple
31 if not origin_type in POSITION_TYPES or\
32 not destination_type in POSITION_TYPES:
33 raise ParserError('Invalid position type')
35 post = settings.search_post
36 post['name_origin'] = origin
37 post['type_origin'] = origin_type
38 post['name_destination'] = destination
39 post['type_destination'] = destination_type
40 post['itdDateDayMonthYear'] = dtime.strftime('%d.%m.%Y')
41 post['itdTime'] = dtime.strftime('%H:%M')
42 params = urlencode(post)
43 url = '%s?%s' % (settings.action, params)
45 print "\nurl %s url\n\n%s\n\nurl %s url\n" % ('~' * 100, url, '~' * 100)
51 """ Parser for search response
54 def __init__(self, html):
55 self.soup = BeautifulSoup(html)
58 if self.soup.find('form', {'id': 'form_efaresults'}):
59 return PageType.RESULT
61 if self.soup.find('div', {'class':'form_error'}):
62 return PageType.CORRECTION
64 return PageType.UNKNOWN
66 def get_correction(self):
67 nlo = self.soup.find('select', {'id': 'nameList_origin'})
68 nld = self.soup.find('select', {'id': 'nameList_destination'})
70 if not nlo and not nld:
71 raise ParserError('Unable to parse html')
74 origin = map(lambda x: x.text, nlo.findAll('option'))
78 destination = map(lambda x: x.text, nld.findAll('option'))
82 return (origin, destination)
85 return rParser(str(self.soup))
90 """ Parser for routing results
93 def __init__(self, html):
94 self.soup = BeautifulSoup(html)
99 def get_tdtext(cls, x, cl):
100 return x.find('td', {'class': cl}).text
103 def get_change(cls, x):
104 y = rParser.get_tdtext(x, 'col_change')
111 def get_price(cls, x):
112 y = rParser.get_tdtext(x, 'col_price')
114 return float(y.replace(',', '.'))
119 def get_date(cls, x):
120 y = rParser.get_tdtext(x, 'col_date')
122 return datetime.strptime(y, '%d.%m.%Y').date()
127 def get_time(cls, x):
128 y = rParser.get_tdtext(x, 'col_time')
130 if (y.find("-") > 0):
131 return map(lambda z: time(*map(int, z.split(':'))), y.split('-'))
133 return map(lambda z: time(*map(int, z.split(':'))), wrap(y, 5))
138 def get_duration(cls, x):
139 y = rParser.get_tdtext(x, 'col_duration')
141 return time(*map(int, y.split(":")))
146 for detail in self.details():
149 def _parse_details(self):
150 tours = self.soup.findAll('div', {'class': 'data_table tourdetail'})
152 trips = map(lambda x: map(lambda y: {
153 'time': rParser.get_time(y),
154 'station': map(lambda z: z[2:].strip(),
155 filter(lambda x: type(x) == NavigableString, y.find('td', {'class': 'col_station'}).contents)), # filter non NaviStrings
156 'info': map(lambda x: x.strip(),
157 filter(lambda z: type(z) == NavigableString, y.find('td', {'class': 'col_info'}).contents)),
158 }, x.find('tbody').findAll('tr')),
164 """returns list of trip details
165 [ [ { 'time': [datetime.time, datetime.time] if time else [],
166 'station': [u'start', u'end'] if station else [],
167 'info': [u'start station' if station else u'details for walking', u'end station' if station else u'walking duration']
168 }, ... # next trip step
169 ], ... # next trip possibility
172 if not self._details:
173 self._details = self._parse_details()
177 def _parse_overview(self):
180 table = self.soup.find('table', {'id': 'tbl_fahrten'})
182 # check if there is an overview table
183 if table and table.findAll('tr'):
185 rows = table.findAll('tr')[1:] # cut off headline
187 overview = map(lambda x: {
188 'date': rParser.get_date(x),
189 'time': rParser.get_time(x),
190 'duration': rParser.get_duration(x), # grab duration
191 'change': rParser.get_change(x),
192 'price': rParser.get_price(x),
196 raise ParserError('Unable to parse overview')
209 if not self._overview:
211 self._overview = self._parse_overview()
212 except AttributeError:
213 f = open('DEBUG', 'w')
214 f.write(str(self.soup))
217 return self._overview
219 if __name__ == '__main__':
220 parser = argparse.ArgumentParser(description='Get public transport route for Vienna')
221 parser.add_argument('-o', metavar='name', type=str, help='origin', required=True)
222 parser.add_argument('-d', metavar='name', type=str, help='destination', required=True)
223 parser.add_argument('-ot', metavar='type', type=str, help='origin type: %s' % ' | '.join(POSITION_TYPES), default='stop', choices=POSITION_TYPES)
224 parser.add_argument('-dt', metavar='type', type=str, help='destination type: %s' % ' | '.join(POSITION_TYPES), default='stop', choices=POSITION_TYPES)
226 args = parser.parse_args()
228 html = search((args.o, args.ot), (args.d, args.dt)).read()
230 parser = sParser(html)
231 state = parser.check_page()
233 if state == PageType.CORRECTION:
235 cor = parser.get_correction()
238 print '* Origin ambiguous:'
240 while not lo or not lo.isdigit() or int(lo) > len(cor[0]):
243 print '%d. %s' % (i, c)
245 lo = sys.stdin.readline().strip()
247 args.o = cor[0][int(lo) - 1]
251 print '* Destination ambiguous:'
253 while not ld or not ld.isdigit() or int(ld) > len(cor[1]):
256 print '%d. %s' % (j, c)
258 ld = sys.stdin.readline().strip()
260 args.d = cor[1][int(ld) - 1]
262 html = search((args.o.encode('UTF-8'), args.ot), (args.d.encode('UTF-8'), args.dt)).read()
264 parser = sParser(html)
265 state = parser.check_page()
268 print 'PANIC at correction page'
270 if state == PageType.RESULT:
271 parser = rParser(html)
273 overviews = parser.overview
274 details = parser.details
277 for r in range(len(overviews)):
278 print '%d. [%s] %s-%s (%s)' % (r + 1, overviews[r]['date'], overviews[r]['time'][0], overviews[r]['time'][1], overviews[r]['duration'])
280 l = sys.stdin.readline().strip()
284 if l.isdigit() and int(l) <= len(details):
285 for detail in details[int(l) - 1]:
286 if detail['time'] and detail['station']:
287 time = '%s - %s' % (detail['time'][0].strftime(TIMEFORMAT), detail['time'][1].strftime(TIMEFORMAT))
288 print '[%s] %s\n%s' % (time, ' -> '.join(detail['station']), '\n'.join(detail['info']))
290 print '\n'.join(detail['info'])
297 elif state == PageType.UNKNOWN:
298 print 'PANIC unknown result'