-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagroscraper.py
More file actions
243 lines (204 loc) · 7.8 KB
/
agroscraper.py
File metadata and controls
243 lines (204 loc) · 7.8 KB
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/bin/env python3
# -*- coding: utf-8 -*-
"""
Extracting information from transparenzdatenbank.at
Output from the #gutedaten Hackathon in Graz, Sat. 28. Nov. 2015
"""
__author__ = "Christopher Kittel"
__copyright__ = "Copyright 2015"
__license__ = "MIT"
__version__ = "0.0.3"
__maintainer__ = "Christopher Kittel"
__email__ = "web@christopherkittel.eu"
__status__ = "Prototype" # 'Development', 'Production' or 'Prototype'
import requests
import os
import sys
import argparse
import json
import csv
parser = argparse.ArgumentParser(description='Extracts structured data from transparenzdatenbank.at and exports it to JSON and CSV.')
parser.add_argument('--output', dest='outputfolder', help='relative or absolute path of the output folder')
parser.add_argument('--year', dest='year', help='year of funding data to request')
args = parser.parse_args()
overall_outfile = "_".join(["agrofunding", args.year]) + ".json"
details_outfile = "_".join(["agrofunding", "details", args.year]) + ".json"
csv_outfile = "_".join(["agrofunding", args.year]) + ".csv"
def drawProgressBar(percent, barLen = 20):
"""
Draw a progress bar to the command line.
"""
sys.stdout.write("\r")
progress = ""
for i in range(barLen):
if i < int(barLen * percent):
progress += "="
else:
progress += " "
sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
sys.stdout.flush()
def get_cache():
"""
If nothing cached, get the raw data.
Returns a tuple of dicts.
"""
try: # load cached search
with open(overall_outfile, "r") as infile:
raw = json.load(infile)
except: # if nothing cached
raw = get_raw()
# make a quick save
with open(overall_outfile, "w") as outfile:
json.dump(raw, outfile)
try: # load cached details
with open(details_outfile, "r") as infile:
results = json.load(infile)
except: # if nothing cached
results = {}
return raw, results
def get_missing_ids(raw, results):
"""
Compare cached results with overall expected IDs, return missing ones.
Returns a set.
"""
all_ids = set(raw.keys())
cached_ids = set(results.keys())
print("There are {0} IDs in the dataset, we already have {1}. {2} are missing.".format(len(all_ids), len(cached_ids), len(all_ids) - len(cached_ids)))
return all_ids - cached_ids
def get_raw():
"""
Perform a POST to transparenzdatenbank asking for the overall raw data.
Returns a dict.
"""
url = 'http://transparenzdatenbank.at/suche'
rawheader = {"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "de,en-US;q=0.7,en;q=0.3",
"Content-Length": "100",
"Content-Type": "application/json;charset=utf-8",
"DNT": "1",
"Host": "transparenzdatenbank.at",
"PAGINATION_CURRENT": "1",
"PAGINATION_PER_PAGE": "140000",
"Referer": "http://transparenzdatenbank.at/",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0"
}
# json string
payload = "{\"name\":\"\", \"betrag_von\":\"\", \"betrag_bis\":\"\", \
\"gemeinde\":\"\", \"massnahme\":null, \
\"jahr\":%s, \"sort\":\"name\"}" %args.year
response = requests.request("POST", url, data=payload, headers = rawheader)
raw = response.json()
return {r.get("id"):r for r in raw}
def crawl(raw, results, missing_ids):
"""
Add missing results by iterating over missing IDs.
Returns a dict.
"""
# for progress bar
progress = 0.0
maxi = len(missing_ids)
i = 0
for id_ in missing_ids:
try:
r = raw.get(id_)
results[id_] = enhance_raw(r)
# more progress
progress += 1
percent = progress/maxi
drawProgressBar(percent)
except: # some server/network error
# store cache
with open(details_outfile, "w") as outfile:
json.dump(results, outfile)
# dumps every 1000 entries to avoid losing progress to network errors
i += 1
if i > 1000:
with open(details_outfile, "w") as outfile:
json.dump(results, outfile)
i = 0
return results
def enhance_raw(r):
"""
Reformat the raw data. Add the detailed information to a raw search result.
Returns a dict.
"""
result = {}
result["id"] = int(r.get("id"))
result["recipient"] = r.get("name")
# missing values for plz
if r.get("plz") is None:
result["postcode"] = "NA"
else:
result["postcode"] = int(r.get("plz"))
result["municipality"] = r.get("gemeinde")
result["year"] = int(r.get("jahr"))
result["total_amount"] = float(r.get("betrag"))
result["details"] = get_details(r.get("id"))
return result
def get_details(id_):
"""
Perform GET requests for the transparenzdatenbank-search and returns
detailed information for a funding ID.
Returns a list.
"""
# create new header for detailed search
detailsheader = {'Host': 'transparenzdatenbank.at',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
'Accept-Encoding': 'gzip, deflate',
'DNT': '1',
'Referer': 'http://transparenzdatenbank.at/'
}
searchurl = 'http://transparenzdatenbank.at/suche/details/%s/%s' %(id_, args.year)
details = []
rawdetails = requests.request("GET", searchurl, headers = detailsheader).json()
for rd in rawdetails:
detail = {}
detail["id"] = int(rd.get("id"))
detail["type"] = rd.get("bezeichnung")
detail["description"] = rd.get("beschreibung")
detail["partial_amount"] = float(rd.get("betrag"))
details.append(detail)
return details
def save2csv(results, filename):
"""
Export the extracted data to agrofunding.csv with the following columns:
"unique_id", "funding_id", "recipient", "year",
"postcode", "municipality", "total_amount",
"detail_id", "type", "partial_amount"
"""
i = 0
with open(filename, "w") as csvfile:
agrowriter = csv.writer(csvfile, delimiter = ",", quotechar='"')
agrowriter.writerow(["unique_id", "funding_id", "recipient", "year",
"postcode", "municipality", "total_amount",
"detail_id", "type", "partial_amount"])
for result in results.values():
metadata = [result.get("id"), result.get("recipient"),
result.get("year"), result.get("postcode"),
result.get("municipality"), result.get("total_amount")]
for detail in result.get("details"):
data = [detail.get("id"), detail.get("type"),
detail.get("partial_amount")]
agrowriter.writerow([i]+metadata+data)
i += 1
def setup_folders(foldername):
"""
Check whether outfolder folder and path exist, create them if necessary.
"""
if not os.path.exists(foldername):
os.makedirs(foldername)
def main(args):
setup_folders(args.outputfolder)
os.chdir(args.outputfolder)
raw, old_results = get_cache()
missing_ids = get_missing_ids(raw, old_results)
new_results = crawl(raw, old_results, missing_ids)
# store final
with open(details_outfile, "w") as outfile:
json.dump(new_results, outfile)
save2csv(new_results, csv_outfile)
if __name__ == '__main__':
main(args)