2 # -*- coding: UTF-8 -*-
4 from BeautifulSoup import BeautifulSoup, NavigableString
5 from urllib2 import urlopen
6 from urllib import urlencode
7 from datetime import datetime, time
8 from textwrap import wrap
13 from gotovienna import defaults
15 POSITION_TYPES = ('stop', 'address', 'poi')
17 DEBUGLOG = os.path.expanduser('~/gotoVienna.debug')
19 class ParserError(Exception):
21 def __init__(self, msg='Parser error'):
25 UNKNOWN, CORRECTION, RESULT = range(3)
28 def search(origin_tuple, destination_tuple, dtime=None):
29 """ build route request
30 returns html result (as urllib response)
33 dtime = datetime.now()
35 origin, origin_type = origin_tuple
36 destination, destination_type = destination_tuple
37 if not origin_type in POSITION_TYPES or\
38 not destination_type in POSITION_TYPES:
39 raise ParserError('Invalid position type')
41 post = defaults.search_post
42 post['name_origin'] = origin
43 post['type_origin'] = origin_type
44 post['name_destination'] = destination
45 post['type_destination'] = destination_type
46 post['itdDateDayMonthYear'] = dtime.strftime('%d.%m.%Y')
47 post['itdTime'] = dtime.strftime('%H:%M')
48 params = urlencode(post)
49 url = '%s?%s' % (defaults.action, params)
52 f = open(DEBUGLOG, 'a')
56 print 'Unable to write to DEBUGLOG: %s' % DEBUGLOG
62 """ Parser for search response
65 def __init__(self, html):
66 self.soup = BeautifulSoup(html)
69 if self.soup.find('form', {'id': 'form_efaresults'}):
70 return PageType.RESULT
72 if self.soup.find('div', {'class':'form_error'}):
73 return PageType.CORRECTION
75 return PageType.UNKNOWN
77 state = property(check_page)
79 def get_correction(self):
80 nlo = self.soup.find('select', {'id': 'nameList_origin'})
81 nld = self.soup.find('select', {'id': 'nameList_destination'})
83 if not nlo and not nld:
84 raise ParserError('Unable to parse html')
87 origin = map(lambda x: x.text, nlo.findAll('option'))
91 destination = map(lambda x: x.text, nld.findAll('option'))
95 return (origin, destination)
98 return rParser(str(self.soup))
103 """ Parser for routing results
106 def __init__(self, html):
107 self.soup = BeautifulSoup(html)
108 self._overview = None
112 def get_tdtext(cls, x, cl):
113 return x.find('td', {'class': cl}).text
116 def get_change(cls, x):
117 y = rParser.get_tdtext(x, 'col_change')
124 def get_price(cls, x):
125 y = rParser.get_tdtext(x, 'col_price')
129 return float(y.replace(',', '.'))
134 def get_date(cls, x):
135 y = rParser.get_tdtext(x, 'col_date')
137 return datetime.strptime(y, '%d.%m.%Y').date()
142 def get_time(cls, x):
143 y = rParser.get_tdtext(x, 'col_time')
145 if (y.find("-") > 0):
146 return map(lambda z: time(*map(int, z.split(':'))), y.split('-'))
148 return map(lambda z: time(*map(int, z.split(':'))), wrap(y, 5))
153 def get_duration(cls, x):
154 y = rParser.get_tdtext(x, 'col_duration')
156 return time(*map(int, y.split(":")))
161 for detail in self.details():
164 def _parse_details(self):
165 tours = self.soup.findAll('div', {'class': 'data_table tourdetail'})
167 trips = map(lambda x: map(lambda y: {
168 'time': rParser.get_time(y),
169 'station': map(lambda z: z[2:].strip(),
170 filter(lambda x: type(x) == NavigableString, y.find('td', {'class': 'col_station'}).contents)), # filter non NaviStrings
171 'info': map(lambda x: x.strip(),
172 filter(lambda z: type(z) == NavigableString, y.find('td', {'class': 'col_info'}).contents)),
173 }, x.find('tbody').findAll('tr')),
179 """returns list of trip details
180 [ [ { 'time': [datetime.time, datetime.time] if time else [],
181 'station': [u'start', u'end'] if station else [],
182 'info': [u'start station' if station else u'details for walking', u'end station' if station else u'walking duration']
183 }, ... # next trip step
184 ], ... # next trip possibility
187 if not self._details:
188 self._details = self._parse_details()
192 def _parse_overview(self):
195 table = self.soup.find('table', {'id': 'tbl_fahrten'})
197 # check if there is an overview table
198 if table and table.findAll('tr'):
200 rows = table.findAll('tr')[1:] # cut off headline
202 overview = map(lambda x: {
203 'date': rParser.get_date(x),
204 'time': rParser.get_time(x),
205 'duration': rParser.get_duration(x), # grab duration
206 'change': rParser.get_change(x),
207 'price': rParser.get_price(x),
211 raise ParserError('Unable to parse overview')
224 if not self._overview:
226 self._overview = self._parse_overview()
227 except AttributeError:
228 f = open(DEBUGLOG, 'w')
229 f.write(str(self.soup))
232 return self._overview