Advertisement
tokarevms

New - Airsearch

Aug 18th, 2017
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.45 KB | None | 0 0
  1. # coding: cp1251
  2. import requests
  3.  
  4.  
  5. class Aeroflot(object):    # Поиск билетов на сайте Аэрофлота
  6.  
  7.     def __init__(self):
  8.         self.search_url = 'https://www.aeroflot.ru/sb/booking/api/app/search/v2'
  9.         self.code_origin = None
  10.         self.code_destination = None
  11.         self.date = None
  12.         self.page = None
  13.         self.city_to = None
  14.         self.city_from = None
  15.  
  16.     def _input_info(self):    # Ввод данных от пользователя
  17.         self.city_from = raw_input('City origin: ')
  18.         self.city_to = raw_input('City destination: ')
  19.         self.date = raw_input('Date ( yyyy-mm-dd): ')
  20.  
  21.     def _check_input(self):    # Поиск введенных городов в библиотеке, определение запроса
  22.         with open('Library.txt', 'r') as libra:
  23.             for line in libra.readlines():
  24.                 if self.city_from in line:
  25.                     self.code_origin = line[:3]
  26.                 elif self.city_to in line:
  27.                     self.code_destination = line[:3]
  28.                 if self.code_destination and self.code_origin:
  29.                     print 'Cities found'
  30.                     self._give_a_page()
  31.                     self._extract_data()
  32.                     break
  33.             else:
  34.                 print 'Cities not found'
  35.  
  36.     def _give_a_page(self):    # Устанавливает успешность запроса
  37.         json_req = {"routes":
  38.                 [{"origin": self.code_origin, "destination": self.code_destination, "departure": self.date}],
  39.                 "cabin": "econom", "award": False, "country": "ru", "adults": 1, "children": 0, "infants": 0,
  40.                 "combined": False, "lang": "ru"}
  41.         respond = requests.post(self.search_url, json=json_req)
  42.         if respond.status_code == 200:
  43.             self.page = respond.json()
  44.             print 'Success request'
  45.         else:
  46.             print 'Invalid request'
  47.             self.page = None
  48.  
  49.     def _extract_data(self):    # Извлекает информацию и записывает в файл
  50.         if self.page is not None:
  51.             self.document.write('\n\nFlights from %s to %s  %s\n'
  52.                            'Code    Airport\Time\Price\n\n' % (self.code_origin, self.code_destination, self.date))
  53.             try:
  54.                 for num in self.page['data']['itineraries'][0]:
  55.                     if len(num['legs'][0]['segments']) != 1:
  56.                         self.document.write('Complex flight\n')
  57.                         continue
  58.                     else:
  59.                         rescode = num['legs'][0]['segments'][0]['operating_flight_number']  # Номер рейса
  60.                         reschr = num['legs'][0]['segments'][0]['airline_code']  # Код рейса
  61.                         resfrom = num['legs'][0]['segments'][0]['origin']['airport_name']  # Аэропорт вылета
  62.                         resto = num['legs'][0]['segments'][0]['destination']['airport_name']  # Аэропорт прилета
  63.                         restravel = num['time_name']  # Время в пути
  64.                         restfrom = num['legs'][0]['segments'][0]['departure_name']  # Время вылета
  65.                         restto = num['legs'][0]['segments'][0]['arrival_name']  # Время прилета
  66.                         price = num['prices'][0]['total_amount']  # Цена, самая низкая из доступных
  67.                         city_name_to = num['legs'][0]['segments'][0]['destination']['city_name']  # Город прилета
  68.                         city_name_from = num['legs'][0]['segments'][0]['origin']['city_name']  # Город вылета
  69.                         print price, reschr + rescode, resto
  70.                         self.document.write(('%-10s %s/%-20s %-25s %-15s %s/%-20s %-25s %s\n' %
  71.                                         (reschr + rescode, city_name_from, resfrom, restfrom, restravel,
  72.                                          resto, city_name_to, restto, price)).encode('cp1251'))
  73.             except IndexError:
  74.                 print 'Flights not found'
  75.                 self.document.write('\n\nFlights not found!\n\n')
  76.  
  77.     def search(self):    # Порядок действий
  78.         with open('ResultAero.txt', 'w') as self.document:
  79.             self._input_info()
  80.             self._check_input()
  81.  
  82. if __name__ == '__main__':
  83.     first = Aeroflot()
  84.     first.search()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement