Advertisement
Guest User

timetable

a guest
Apr 24th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.36 KB | None | 0 0
  1. import requests
  2. import datetime
  3. from getpass import getpass
  4. from bs4 import BeautifulSoup
  5. from math import floor
  6.  
  7. DEFAULT_TOTAL_MONTHS = 3
  8.  
  9. def login(user,passw):
  10.     data_form = {'empresa':'a128879', 'matricula':user, 'senha':passw}
  11.     return requests.post('https://www.ahgora.com.br/externo/login', data_form)
  12.  
  13. def requestTables(cookies, month=''):
  14.     response = requests.get('https://www.ahgora.com.br/externo/batidas/'+month, cookies=cookies)
  15.     page_soup = BeautifulSoup(response._content, 'html.parser')
  16.     tables = page_soup.find_all('table', class_="table table-bordered table-striped")
  17.     return tables
  18.  
  19. def isTotalsTable(table):
  20.     return table.has_attr('id')
  21.  
  22. def parseTotals(table):
  23.     return {}
  24.  
  25. def parseTimetable(table):
  26.     days = []
  27.     for row in table.tbody.find_all('tr'):
  28.         c  = row.contents[1].contents
  29.         if len(c) > 12:
  30.             date = c[0].strip()
  31.             batidas = ''.join(c[3].stripped_strings)
  32.             results = list(s.strip() for s in c[11].strings)
  33.             hours_worked = getHoursWorked(results)
  34.             balance = getBalance(results)
  35.             balance_min = time2mins(balance)
  36.             days.append( {'date':date, 'batidas':batidas, 'hours_worked':hours_worked, 'balance':balance, 'balance_min':balance_min } )
  37.     return days
  38.  
  39. def getHoursWorked(results):
  40.     for i in results:
  41.         if i.startswith('Horas Trabalhadas: '):
  42.             return i[19:]
  43.     return ''
  44.    
  45. def getBalance(results):
  46.     for i in results:
  47.         if i.startswith('Banco de Horas: '):
  48.             return i[16:]
  49.     return ''
  50.  
  51. def time2mins(time_str):
  52.     nums = time_str.split(':')
  53.     if len(nums) >= 2:
  54.         hours = int(nums[0])
  55.         mins = int(nums[1])
  56.         return 60*hours - mins if time_str.startswith('-') else 60*hours + mins
  57.     else:
  58.         return 0
  59.  
  60. def getDate(item):
  61.     return datetime.datetime.strptime(item['date'], '%d/%m/%Y')
  62.  
  63. if __name__ == '__main__':
  64.     print('Matricula:')
  65.     u = input()
  66.     p = getpass("Senha:\n")
  67.    
  68.     try:
  69.         totalMonths = int(input('Deseja buscar quantos meses? [default={}]\n'.format(DEFAULT_TOTAL_MONTHS)))
  70.     except ValueError:
  71.         totalMonths = DEFAULT_TOTAL_MONTHS
  72.    
  73.     print('Fazendo login...')
  74.     full_data = []
  75.     session_cookies = login(u,p).cookies
  76.    
  77.    
  78.     months = ['']
  79.     today = datetime.date.today()
  80.    
  81.     for i in range(totalMonths-1):
  82.         month = (today.month + 10 - i) % 12 + 1
  83.         year = today.year - floor((1 + i - today.month)/12) - 1
  84.         months.append('{:02d}-{:04d}'.format(month, year))
  85.    
  86.     for month in months:
  87.         print('Buscando dados do mes {}...'.format(month if month else 'atual'))
  88.         tables = requestTables(session_cookies, month)
  89.        
  90.         for t in tables:
  91.             if isTotalsTable(t):
  92.                 parseTotals(t)
  93.             else:
  94.                 full_data += parseTimetable(t)
  95.              
  96.     full_data = sorted(full_data, key=getDate)
  97.    
  98.     output_file = open('horarios.csv', 'w')
  99.     output_file.write('Data; Batidas; Horas Trabalhadas; Saldo; Saldo (minutos)\n')
  100.     for entry in full_data:
  101.         output_file.write('{}; {}; {}; {}; {}\n'.format(entry['date'], entry['batidas'], entry['hours_worked'], entry['balance'], entry['balance_min']))
  102.     output_file.close()
  103.     print('Pronto! Arquivo \'horarios.csv\' criado.')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement