Skip to content

Commit adf0262

Browse files
committed
Use FTS API for scraper, fixes #39
1 parent f9e597c commit adf0262

2 files changed

Lines changed: 18 additions & 34 deletions

File tree

requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
requests
2-
openpyxl

scraper.py

Lines changed: 18 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,30 @@
1-
from datetime import datetime
2-
import html
31
from os.path import join
4-
from io import BytesIO
52
import csv
3+
from operator import itemgetter
64

75
import requests
8-
import openpyxl
96

10-
def to_date(date_str):
11-
return datetime.strptime(date_str, '%d %B %Y').date()
7+
url = 'https://api.hpc.tools/v2/public/plan'
8+
headers = ['Plan name', 'Plan code', 'Plan type', 'Plan year', 'Start date', 'End date']
129

13-
# via https://fts.unocha.org/plan-code-list-iati
14-
url = 'https://fts.unocha.org/download/initiate/views_executable/xlsx?uri=/plan-code-list-iati&query%5Buri%5D=/plan-code-list-iati&query%5Bview_id%5D=plan_code_list_for_iati&query%5Bview_display%5D=page&query%5B_wrapper_format%5D=drupal_modal&view_id=plan_code_list_for_iati&view_display=page'
1510
r = requests.get(url)
16-
download_id = r.json()[0].get('download_id')
17-
18-
r = requests.get(f'https://fts.unocha.org/download/{download_id}/download')
19-
wb = openpyxl.load_workbook(BytesIO(r.content))
20-
sheet = wb['Export data']
21-
rows = [
22-
[
23-
html.unescape(str(cell.value)) if cell.value is not None else None
24-
for cell in row
25-
] for row in sheet.rows]
26-
27-
# bin the first 2 rows
28-
rows = rows[2:]
29-
30-
# pop the header row
31-
headers = rows.pop(0)
32-
33-
# standardise headers
34-
headers = [h[0] + h[1:].lower() for h in headers]
35-
36-
# zip it up
37-
rows = [dict(zip(headers, row)) for row in rows]
11+
data = r.json()
12+
rows = []
3813

3914
# fix the dates
40-
for row in rows:
41-
row['Start date'] = to_date(row['Start date'])
42-
row['End date'] = to_date(row['End date'])
15+
for item in data['data']:
16+
rows.append({
17+
'Plan name': item['planVersion']['name'],
18+
'Plan code': item['planVersion']['code'],
19+
'Plan type': ",".join([it['name'] for it in item['categories'] if it['group'] == 'planType']),
20+
'Plan year': ",".join([it['year'] for it in item['years']]),
21+
'Start date': item['planVersion']['startDate'],
22+
'End date': item['planVersion']['endDate'],
23+
})
24+
25+
26+
rows.sort(key=itemgetter('Plan name'))
27+
rows.sort(key=itemgetter('Plan year'), reverse=True)
4328

4429
with open(join('output', 'humanitarian-plan.csv'), 'w') as f:
4530
writer = csv.DictWriter(f, fieldnames=headers)

0 commit comments

Comments
 (0)