-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathogimet.py
203 lines (174 loc) · 7.66 KB
/
ogimet.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import requests
from lxml import html
from calendar import monthrange
from dateutil.rrule import rrule, MONTHLY
from datetime import datetime
import os
from sys import argv
class Downloader():
"""docstring for Downloader."""
def __init__(self):
if os.getcwd().__contains__("\\"):
self.sep = "\\"
else:
self.sep = "/"
self.temptcolnames = ['Max', 'Min', 'Avg']
self.windcolnames = ['Dir.', 'Int.']
self.sumcolnames = ['03', '06', '09', '12', '15', '18', '21', '24']
self.comb = {}
def month_iter(self, start_month, start_year, end_month, end_year):
start = datetime(start_year, start_month, 1)
end = datetime(end_year, end_month, 1)
r = ((d.month, d.year) for d in rrule(MONTHLY,dtstart=start, until=end))
return r
def tryGetTable(self, tree, year, month, attempt=10):
if attempt == 0:
return "Fail"
try:
return tree.xpath('//table[@border="0"]')[0]
except:
tree = self.requestData(self.linkConstructor(year, month))
self.tryGetTable(tree, year, month, attempt=attempt-1)
def requestData(self,link, attempt=10):
if attempt == 0:
return "Fail"
page = requests.get(link)
noSummary=page.content.__str__().__contains__('summary')
if any( [page.status_code != 200, not noSummary ]):
requestData(link, attempt=attempt-1)
tree = html.fromstring(page.content)
return tree
def running_all(self, end_year, end_month, start_year=2000, start_month=1,\
stationid="97240", location=os.getcwd()):
self.stationid = stationid
#make directory
dir_name = stationid + "-" + str(start_year) + str(start_month) + "-"+\
str(end_year)+ str(end_month)
try:
os.mkdir(location + self.sep + dir_name )
except FileExistsError:
print("direcory already exist")
self.location = location + self.sep + dir_name
for m in self.month_iter(start_month, start_year, end_month, end_year):
print("running " + m[1].__str__() + "-" + m[0].__str__() )
self.completeRun(m[1], m[0])
def linkConstructor(self, year, month):
link = "https://www.ogimet.com/cgi-bin/gsynres?lang=en&ind="+ \
self.stationid +"&ndays=" + monthrange(year, month)[1].__str__() + \
"&ano=" + year.__str__() + "&mes=" + "%02d" % month + "&day=" + \
"%02d" % monthrange(year, month)[1] + "&hora=00&ord=REV&Send=Send"
return link
def requestData(self,link, attempt=10):
if attempt == 0:
return "Fail"
page = requests.get(link)
noSummary= page.content.__str__().__contains__('summary')
if any( [page.status_code != 200, not noSummary ]):
self.requestData(link, attempt=attempt-1)
tree = html.fromstring(page.content)
return tree
def completeRun(self, year, month):
link = self.linkConstructor(year, month)
print(link)
data = self.requestData(link)
self.writeData(data, year, month, self.location, '')
def failDetector(self, year, month):
with open('report.log', 'a') as report:
report.write(year.__str__() + "-" + month.__str__() + "\n")
def getcolum(self, table):
colnames = []
for a in table.getchildren()[1][0][:]:
if a.text_content().__contains__("Temperature"):
for b in table.getchildren()[1][1]:
if self.temptcolnames.__contains__(b.text_content()):
col = a.text_content() + b.text_content()
colnames.append(col)
elif a.text_content().__contains__("Wind"):
for b in table.getchildren()[1][1]:
if self.windcolnames.__contains__(b.text_content()):
col = a.text_content() + b.text_content()
colnames.append(col)
elif a.text_content().__contains__("summary"):
for c in self.sumcolnames:
col = a.text_content() + c
colnames.append(col)
else:
col = a.text_content()
colnames.append(col)
return colnames
def writeData(self,tree, year, month, location, basename=''):
if tree == "Fail":
self.failDetector(year, month)
return 0
table = self.tryGetTable(tree, year, month)
if table == "Fail":
self.failDetector(year, month)
return 0
colnames = self.getcolum(table)
caption = table.getchildren()[0]
tr = table.getchildren()[2:monthrange(year, month)[1] + 2]
monthly = 0
na = 0
for a in tr[::-1]:
data = {}
id = 0
for colname in colnames:
try:
data[colname] = a.getchildren()[id].text_content()
except:
data[colname] = 'No Data'
id = id + 1
name = self.sep + basename + 'data' + year.__str__() + '-' +\
"%02d" % month + '-' + data['Date'].split("/")[1] + '.csv'
self.comb[name]=data
for key, value in data.items():
timestamp = year.__str__() + "-%02d-" % month + \
data['Date'].split("/")[1]
self.writecsv(key, timestamp , value)
#### additional for botir requests
if key.__contains__("Prec"):
if value == 'Tr':
value = 0
if any ( [value == '----' , value == 'No data']):
value = 'NA'
na = na + 1
else:
monthly = monthly + float(value)
#### write monthly data
filename = self.location + self.sep + "monthly-prec" + ".csv"
filename2 = self.location + self.sep + "monthly-prec-na" + ".csv"
time = year.__str__() + "-%02d" % month
with open(filename, 'a') as csv_file:
csv_file.write("%s, %s\n" % (time, str(monthly)))
with open(filename2, 'a') as csv_file2:
csv_file2.write("%s, %s\n" % (time, str(na)))
def writecsv(self, key, timestamp, val):
if not key.endswith("."):
filename = self.location + self.sep + key + ".csv"
elif key.__contains__("/"):
newkey = key.split("/")[0] + key.split("/")[1]
filename = self.location + self.sep + newkey + "csv"
else:
filename = self.location + self.sep + key + "csv"
with open(filename, 'a') as csv_file:
if any ( [val == '----' , val == 'No data']):
val = 'NA'
if val == 'Tr':
val = 0
csv_file.write("%s, %s\n" % (timestamp, val))
if __name__ == '__main__':
cont = True
try:
script, yend, mend, ystart, mstart, stationid = argv
except:
format = '(end-year) (end-month) (start-year) (start-month) (stationid)'
print("usage >>>> python ogimet.py " + format)
print("example >>>>> python ogimet.py 2019 5 2019 1 97240")
print(" WARNING!!!!: DO NOT OPEN THE FILE WHILE DOWNLOADED!!!!")
cont = False
if cont:
D = Downloader()
#D.running_all(2019, 5, start_year=2019, start_month=1,\
#stationid="97240"
D.running_all(int(yend), int(mend), int(ystart), int(mstart), stationid)
print("Enjoy you data :) ")