This repository has been archived by the owner on Aug 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OApiExtr.py
214 lines (183 loc) · 8.13 KB
/
OApiExtr.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
204
205
206
207
208
209
210
211
212
213
214
###python 3.6
#!/usr/bin/env python
import ujson
import pandas as pd
from urllib.request import Request
import urllib
import sys
from pick import pick
from urllib.parse import urlsplit
import flattener
class jsonScraper:
def __init__(self, url, selType):
self.sourceUrl = url
baseUrl = urlsplit(url)
self.baseUrl = baseUrl.scheme + '://' + baseUrl.hostname
self.filename = url.replace('https://', '').replace('http://', '').replace('/', '')
self.filename = self.filename + '.csv'
self.nextUrl = None
self.dfList = []
if selType == 0:
self.convertLoop()
else:
self.chosen = False
self.convertLoopSelect()
def convertLoop(self):
tempDf = self.converter(self.sourceUrl)
self.dfList.append(tempDf)
# print(self.sourceUrl)
# print(self.nextUrl)
if self.sourceUrl != self.nextUrl:
self.sourceUrl = self.nextUrl
try:
self.convertLoop()
except TimeoutError:
print(self.sourceUrl)
except KeyboardInterrupt:
self.finalDf = pd.concat(self.dfList)
print('files collected')
self.finalDf.to_csv(str(self.filename), index=False)
else:
self.finalDf = pd.concat(self.dfList)
print('all files collected')
self.finalDf.to_csv(str(self.filename), index=False)
def convertLoopSelect(self):
tempDf = self.converter(self.sourceUrl)
if self.chosen == False:
title = 'Please choose the columns you want to include in your csv file (press SPACE to mark, ENTER to continue): '
coloptions = tempDf.columns
self.selected = pick(coloptions, title, multi_select=True, min_selection_count=1)
self.chosen = True
self.dfList.append(tempDf)
if self.sourceUrl != self.nextUrl:
self.sourceUrl = self.nextUrl
try:
self.convertLoopSelect()
except TimeoutError:
print(self.sourceUrl)
except KeyboardInterrupt:
self.finalDf = pd.concat(self.dfList)
print('files collected')
col_selection = []
for col in self.selected:
col_selection.append(col[0])
selected_finalDf = self.finalDf[col_selection]
selected_finalDf.to_csv(str(self.filename), index=False)
else:
self.finalDf = pd.concat(self.dfList)
print('all files collected')
col_selection = []
for col in self.selected:
col_selection.append(col[0])
selected_finalDf = self.finalDf[col_selection]
selected_finalDf.to_csv(str(self.filename), index=False)
def pageLoad(self, extUrl):
try:
with urllib.request.urlopen(extUrl) as url:
data = ujson.loads(url.read().decode())
self.nextUrl = data['next']
return data['items']
except (urllib.error.HTTPError):
req = Request(extUrl, headers={'User-Agent': 'Mozilla/5.0'})
try:
url = urllib.request.urlopen(req)
data = ujson.loads(url.read().decode())
self.nextUrl = data['next']
return data['items']
except (urllib.error.HTTPError):
# self.finalDf = pd.concat(self.dfList)
# print('files collected')
# self.finalDf.to_csv(str(self.filename), index=False)
print('HTTP error')
except ValueError as e:
extUrl = self.baseUrl + extUrl
try:
with urllib.request.urlopen(extUrl) as url:
data = ujson.loads(url.read().decode())
self.nextUrl = data['next']
return data['items']
except (urllib.error.HTTPError):
# time.sleep(120)
req = Request(extUrl, headers={'User-Agent': 'Mozilla/5.0'})
url = urllib.request.urlopen(req)
data = ujson.loads(url.read().decode())
self.nextUrl = data['next']
return data['items']
def converter(self, myUrl):
extJson = self.pageLoad(myUrl)
newJson = []
# counter = 0
if extJson is not None:
for i in extJson:
# print(i.keys())
if 'data' in i.keys():
data = flattener.splitObj(i['data'])
if data[0] is not None and data[2] is None:
data = data[0]
elif data[0] is not None and data[2] is not None:
data_plus = flattener.splitObj(data[2][0], prefix=data[1])
data = data[0]
if data_plus[0] is not None:
data = {**data, **data_plus[0]}
# counter = 0
else:
#we go down another level
data = flattener.splitObj(data[2][0], prefix=data[1])
if data[0] is not None and data[2] is None:
data = data[0]
elif data[0] is not None and data[2] is not None:
data_plus = flattener.splitObj(data[2][0], prefix=data[1])
data = data[0]
if data_plus[0] is not None:
data = {**data, **data_plus[0]}
else:
data = flattener.splitObj(data[2][0], prefix=data[1])
if data[0] is not None and data[2] is None:
data = data[0]
elif data[0] is not None and data[2] is not None:
data_plus = flattener.splitObj(data[2][0], prefix=data[1])
data = data[0]
if data_plus[0] is not None:
data = {**data, **data_plus[0]}
i.pop('data', None)
try:
j = {**i, **data}
newJson.append(j)
except TypeError:
data = flattener.splitObj(data[2][0], prefix=data[1])
if data[0] is not None and data[2] is None:
data = data[0]
elif data[0] is not None and data[2] is not None:
data_plus = flattener.splitObj(data[2][0], prefix=data[1])
data = data[0]
if data_plus[0] is not None:
data = {**data, **data_plus[0]}
else:
data = flattener.splitObj(data[2][0], prefix=data[1])
if data[0] is not None and data[2] is None:
data = data[0]
elif data[0] is not None and data[2] is not None:
data_plus = flattener.splitObj(data[2][0], prefix=data[1])
data = data[0]
if data_plus[0] is not None:
data = {**data, **data_plus[0]}
try:
j = {**i, **data}
newJson.append(j)
except TypeError:
print(i, data)
continue
apiDF = pd.DataFrame(newJson)
return apiDF
else:
apiDF = pd.DataFrame()
return apiDF
def main():
# my code here
jsonUrl = sys.argv[1]
title = 'Please choose your favourite extraction mode: '
options = ['all variables', 'selected variables']
option, index = pick(options, title)
x = jsonScraper(jsonUrl, index)
if __name__ == "__main__":
main()