-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
81 lines (56 loc) · 1.88 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import datetime
import os
import pickle
import requests
from bs4 import BeautifulSoup
from multiprocessing.dummy import Pool
DETRO = 'http://www.detro.rj.gov.br/regulares-tarifas-itinerario/include/linhas.php?parametro=%s'
LINES_PAGE = 'http://www.detro.rj.gov.br/regulares-tarifas-itinerario/'
PARALLEL_RUNS = 40
FILEFORMAT = 'assets/%s.txt'
PARALLEL = False
CHANGES = 'changes.txt'
def download_contents(param_id):
return requests.get(DETRO % param_id).content
def get_line_codes():
soup = BeautifulSoup(requests.get(LINES_PAGE).content, 'html.parser')
return {x.attrs['value']: x.text for x in soup.find(id='linhas').findAll('option')}
def dumpfile(key, content):
with open(FILEFORMAT % key, '+wb') as file:
pickle.dump(content, file)
def logchanges(text, message):
with open(CHANGES, 'a') as changes:
changes.write(('%s - ' + message) % (datetime.datetime.now(), text))
def process(item):
""" Item like (key, text)"""
key, text = item
if not key or key == ' ':
return
content = download_contents(key).decode('utf-8')
if not check_has_file(key):
logchanges(text, 'Line Added: "%s"\n')
dumpfile(key, content)
return
with open(FILEFORMAT % key, 'rb') as file:
original = pickle.load(file)
if original != content:
logchanges(text, 'Line Changed: "%s"\n')
dumpfile(key, content)
return {
'key': key,
'text': text
}
def check_has_file(key):
return os.path.isfile(FILEFORMAT % key)
if __name__ == '__main__':
pool = Pool(PARALLEL_RUNS)
lines = get_line_codes()
lines = [(x, lines[x]) for x in lines]
logchanges('', '---------------------------%s\n')
logchanges('', 'Running...%s\n')
if PARALLEL:
pool.map(process, lines)
else:
for line in lines:
process(line)
logchanges('', 'OK%s\n')