home · contact · privacy
De-hardcode March the 10th.
[berlin-corona-table] / scrape.py
1 #!/usr/bin/env python3
2 import urllib.request
3 import datetime
4 import bs4
5 import re
6
7 url_prefix = 'https://www.berlin.de'
8 pm_dir = '/sen/gpg/service/presse/2020/'
9 pm_nav_path = pm_dir + '?page_at_1_0='
10
11 # Map abbreviations to full names (and their alternate spellings).
12 abbrevs = {
13   'CW': {'Charlottenburg-Wilmersdorf'},
14   'FK': {'Friedrichshain-Kreuzberg'},
15   'Li': {'Lichtenberg'},
16   'MH': {'Marzahn-Hellersdorf'},
17   'Mi': {'Mitte'},
18   'Ne': {'Neukölln', 'Neuköln'},
19   'Pa': {'Pankow'},
20   'Re': {'Reinickendorf'},
21   'Sp': {'Spandau'},
22   'SZ': {'Steglitz-Zehlendorf'},
23   'TS': {'Tempelhof-Schöneberg'},
24   'TK': {'Treptow-Köpenick'},
25   'sum': {'Summe', 'Berlin'},
26 }
27
28 # some pre-filled values
29 data = {
30    # For these, only image files are available for the table data.
31     datetime.datetime(2020, 7, 2): {
32         'CW': {'growth': 4, 'total': 851},
33         'FK': {'growth': 10, 'total': 681},
34         'Li': {'growth': 3, 'total': 427},
35         'MH': {'growth': 4, 'total': 468},
36         'Mi': {'growth': 0, 'total': 1202},
37         'Ne': {'growth': 7, 'total': 1031},
38         'Pa': {'growth': 3, 'total': 784},
39         'Re': {'growth': 6, 'total': 660},
40         'Sp': {'growth': 3, 'total': 450},
41         'SZ': {'growth': 0, 'total': 591},
42         'TS': {'growth': 3, 'total': 798},
43         'TK': {'growth': 0, 'total': 401},
44         'sum': {'growth': 43, 'total': 8344}
45     },
46     datetime.datetime(2020, 4, 5): {
47         'CW': {'growth': 9, 'total': 462},
48         'FK': {'growth': 2, 'total': 352},
49         'Li': {'growth': 0, 'total': 142},
50         'MH': {'growth': 3, 'total': 127},
51         'Mi': {'growth': 14, 'total': 537},
52         'Ne': {'growth': 0, 'total': 392},
53         'Pa': {'growth': 10, 'total': 378},
54         'Re': {'growth': 9, 'total': 248},
55         'Sp': {'growth': 3, 'total': 150},
56         'SZ': {'growth': 0, 'total': 312},
57         'TS': {'growth': 8, 'total': 394},
58         'TK': {'growth': 3, 'total': 193},
59         'sum': {'growth': 61, 'total': 3687}
60     },
61     datetime.datetime(2020, 4, 4): {
62         'CW': {'growth': 2, 'total': 453},
63         'FK': {'growth': 7, 'total': 350},
64         'Li': {'growth': 0, 'total': 142},
65         'MH': {'growth': 15, 'total': 124},
66         'Mi': {'growth': 22, 'total': 523},
67         'Ne': {'growth': 15, 'total': 392},
68         'Pa': {'growth': 10, 'total': 368},
69         'Re': {'growth': 5, 'total': 239},
70         'Sp': {'growth': 21, 'total': 147},
71         'SZ': {'growth': 12, 'total': 312},
72         'TS': {'growth': 24, 'total': 386},
73         'TK': {'growth': 7, 'total': 190},
74         'sum': {'growth': 140, 'total': 3626}
75     },
76     datetime.datetime(2020, 4, 3): {
77         'CW': {'growth': 44, 'total': 451},
78         'FK': {'growth': 17, 'total': 343},
79         'Li': {'growth': 7, 'total': 142},
80         'MH': {'growth': 4, 'total': 109},
81         'Mi': {'growth': 4, 'total': 501},
82         'Ne': {'growth': 40, 'total': 377},
83         'Pa': {'growth': 39, 'total': 358},
84         'Re': {'growth': 26, 'total': 234},
85         'Sp': {'growth': 9, 'total': 126},
86         'SZ': {'growth': 18, 'total': 300},
87         'TS': {'growth': 41, 'total': 362},
88         'TK': {'growth': 14, 'total': 183},
89         'sum': {'growth': 263, 'total': 3486}
90     },
91    # Here the totals needed to be reconstructed.
92    datetime.datetime(2020, 3, 9): {
93         'CW': {'growth': 4, 'total': 13},
94         'FK': {'growth': 3, 'total': 12},
95         'Li': {'growth': 0, 'total': 1},
96         'MH': {'growth': 1, 'total': 2},
97         'Mi': {'growth': 0, 'total': 8},
98         'Ne': {'growth': 1, 'total': 3},
99         'Pa': {'growth': 1, 'total': 6},
100         'Re': {'growth': 0, 'total': 3},
101         'Sp': {'growth': 0, 'total': 2},
102         'SZ': {'growth': 0, 'total': 3},
103         'TS': {'growth': 0, 'total': 5},
104         'TK': {'growth': 0, 'total': 0},
105         'sum': {'growth': 10, 'total': 58}
106    },
107    # Here the growth numbers needed to be reconstructed.
108    datetime.datetime(2020, 3, 8): {
109         'CW': {'growth': 0, 'total': 9},
110         'FK': {'growth': 4, 'total': 9},
111         'Li': {'growth': 1, 'total': 1},
112         'MH': {'growth': 0, 'total': 1},
113         'Mi': {'growth': 0, 'total': 8},
114         'Ne': {'growth': 0, 'total': 2},
115         'Pa': {'growth': 0, 'total': 5},
116         'Re': {'growth': 0, 'total': 3},
117         'Sp': {'growth': 2, 'total': 2},
118         'SZ': {'growth': 1, 'total': 3},
119         'TS': {'growth': 0, 'total': 5},
120         'TK': {'growth': 0, 'total': 0},
121         'sum': {'growth': 8, 'total': 48}
122    },
123    # Here the growth numbers needed to be reconstructed.
124    datetime.datetime(2020, 3, 7): {
125         'CW': {'growth': 6, 'total': 9},
126         'FK': {'growth': 1, 'total': 5},
127         'Li': {'growth': 0, 'total': 0},
128         'MH': {'growth': 0, 'total': 1},
129         'Mi': {'growth': 1, 'total': 8},
130         'Ne': {'growth': 0, 'total': 2},
131         'Pa': {'growth': 1, 'total': 5},
132         'Re': {'growth': 0, 'total': 3},
133         'Sp': {'growth': 0, 'total': 0},
134         'SZ': {'growth': 2, 'total': 2},
135         'TS': {'growth': 1, 'total': 5},
136         'TK': {'growth': 0, 'total': 0},
137         'sum': {'growth': 12, 'total': 40}
138    },
139    # Here the growth numbers needed to be reconstructed.
140    datetime.datetime(2020, 3, 6): {
141         'CW': {'growth': 1, 'total': 3},
142         'FK': {'growth': 0, 'total': 4},
143         'Li': {'growth': 0, 'total': 0},
144         'MH': {'growth': 0, 'total': 1},
145         'Mi': {'growth': 4, 'total': 7},
146         'Ne': {'growth': 1, 'total': 2},
147         'Pa': {'growth': 1, 'total': 4},
148         'Re': {'growth': 0, 'total': 3},
149         'Sp': {'growth': 0, 'total': 0},
150         'SZ': {'growth': 0, 'total': 0},
151         'TS': {'growth': 2, 'total': 4},
152         'TK': {'growth': 0, 'total': 0},
153         'sum': {'growth': 9, 'total': 28}
154    },
155    # Here the growth numbers needed to be reconstructed.
156    datetime.datetime(2020, 3, 5): {
157         'CW': {'growth': 2, 'total': 2},
158         'FK': {'growth': 0, 'total': 4},
159         'Li': {'growth': 0, 'total': 0},
160         'MH': {'growth': 0, 'total': 1},
161         'Mi': {'growth': 0, 'total': 3},
162         'Ne': {'growth': 0, 'total': 1},
163         'Pa': {'growth': 1, 'total': 3},
164         'Re': {'growth': 2, 'total': 3},
165         'Sp': {'growth': 0, 'total': 0},
166         'SZ': {'growth': 0, 'total': 0},
167         'TS': {'growth': 1, 'total': 2},
168         'TK': {'growth': 0, 'total': 0},
169         'sum': {'growth': 6, 'total': 19}
170    },
171    # Here the growth numbers needed to be reconstructed.
172    datetime.datetime(2020, 3, 4): {
173         'CW': {'growth': 0, 'total': 0},
174         'FK': {'growth': 2, 'total': 4},
175         'Li': {'growth': 0, 'total': 0},
176         'MH': {'growth': 0, 'total': 1},
177         'Mi': {'growth': 0, 'total': 3},
178         'Ne': {'growth': 0, 'total': 1},
179         'Pa': {'growth': 1, 'total': 2},
180         'Re': {'growth': 1, 'total': 1},
181         'Sp': {'growth': 0, 'total': 0},
182         'SZ': {'growth': 0, 'total': 0},
183         'TS': {'growth': 0, 'total': 1},
184         'TK': {'growth': 0, 'total': 0},
185         'sum': {'growth': 4, 'total': 13}
186    },
187    # Here the growth numbers needed to be reconstructed.
188    datetime.datetime(2020, 3, 3): {
189         'CW': {'growth': 0, 'total': 0},
190         'FK': {'growth': 2, 'total': 2},
191         'Li': {'growth': 0, 'total': 0},
192         'MH': {'growth': 0, 'total': 1},
193         'Mi': {'growth': 0, 'total': 3},
194         'Ne': {'growth': 0, 'total': 1},
195         'Pa': {'growth': 1, 'total': 1},
196         'Re': {'growth': 0, 'total': 0},
197         'Sp': {'growth': 0, 'total': 0},
198         'SZ': {'growth': 0, 'total': 0},
199         'TS': {'growth': 0, 'total': 1},
200         'TK': {'growth': 0, 'total': 0},
201         'sum': {'growth': 3, 'total': 9}
202    },
203 }
204 fixes = {
205    # Here the official total is 215, while the summation of district
206    # numbers only adds up to 125 – pretty much looks like a mere
207    # transposition of digits.
208    datetime.datetime(2020, 3, 27): {
209        'sum': {
210            'growth': 125
211        }
212    },
213    # Here the official total is 1937, while the summation of district
214    # numbers only adds up to 1917; furthermore, the original value for
215    # SZ is 118 (+18), which makes no sense, as the day before is
216    # 120 (+15) and the day after is 147 (+15).  The following is a
217    # compromise to keep as many surrounding numbers stable as possible.
218    datetime.datetime(2020, 3, 26): {
219        'SZ': {
220            'growth': 12
221        },
222        'sum': {
223            'growth': 286
224        }
225    },
226    # Here the official total is 220, while the summation of district
227    # numbers adds up to 228 – looks like someone misread an 8 as a 0.
228    datetime.datetime(2020, 3, 25): {
229        'sum': {
230            'growth': 220
231        }
232    },
233 }
234
235 # Scan navigation bar for maximum pagination value.
236 url = url_prefix + pm_dir
237 with urllib.request.urlopen(url) as response:
238    html = response.read()
239 soup = bs4.BeautifulSoup(html, 'html.parser')
240 max_page=0
241 for link in soup.find_all('a'):
242     href = link['href']
243     if str.startswith(href, pm_nav_path):
244         max_test = int(href.split('=')[1])
245         max_page = max_test if max_test > max_page else max_page
246
247 # Scan paginated press release links for daily Corona number briefing links.
248 day_urls = []
249 for i in range(max_page):
250     url = url_prefix + pm_nav_path + str(i + 1)
251     with urllib.request.urlopen(url) as response:
252         html = response.read()
253     soup = bs4.BeautifulSoup(html, 'html.parser')
254     for link in soup.find_all('a'):
255         if (not link.string) or\
256            (not link.string.startswith('Coronavirus: Derzeit') and
257             not link.string.startswith('Coronavirus in Berlin: Bestätigte Fälle')):
258             continue
259         day_urls += [link['href']]
260
261 # Collect infection data.
262 first_run = True
263 districts_sorted = []
264 date_limit = datetime.datetime(2020, 3, 11)
265 for path in day_urls:
266     url = url_prefix + path
267     with urllib.request.urlopen(url) as response:
268         html = response.read()
269     soup = bs4.BeautifulSoup(html, 'html.parser')
270     date_title = soup.find('div', class_='pressnumber')
271     m = re.search('[0-9]+\\.[0-9]+\\.[0-9]+', date_title.string)
272     date_formatted = m.group(0)
273     date = datetime.datetime.strptime(date_formatted , '%d.%m.%Y')
274     if date_limit > date:
275         break
276     # On that day, two press releases were released, for that and the prev day.
277     if date == datetime.datetime(2020, 3, 15) and date in data:
278        date = datetime.datetime(2020, 3, 14)
279     # From here on, press releases describe numbers from prev day.
280     if date <= datetime.datetime(2020, 3, 13):
281        date = date - datetime.timedelta(days=1)
282     table = soup.find('table')
283     # For 13th of March we lack a press release.
284     if table is None and (date in data or date == datetime.datetime(2020, 3, 13)):
285         continue
286     data[date] = {}
287     for tr in [tr for tr in table.children if type(tr) == bs4.element.Tag][1:]:
288          printable_tds = []
289          for td in [td for td in tr.children if type(td) == bs4.element.Tag][:2]:
290              printable_string = ' '.join([s for s in td.strings])
291              printable_tds += [printable_string.strip()]
292          district_long = printable_tds[0]
293          district_short = [k for k in abbrevs if district_long in abbrevs[k]][0]
294          if first_run:
295              districts_sorted += [district_short]
296          if date == datetime.datetime(2020, 3, 10):
297             # For this date we only get totals.
298             data[date][district_short] = {'total': int(printable_tds[1])}
299          else:
300              split_char = ' '
301              if not split_char in printable_tds[1]:
302                  split_char = '('
303              total_str, growth_str = printable_tds[1].split(split_char)
304              growth = int(growth_str.replace('(', '').replace(')', '').\
305                           replace('+', ''))
306              total = int(total_str.replace('.', ''))
307              data[date][district_short] = {'growth': growth, 'total': total}
308     first_run = False
309
310 def neighbor_days(day_target):
311    day_delta = datetime.timedelta(days=1)
312    return day_target + day_delta, day_target - day_delta
313
314 # Reconstruct growth for 10th of March.
315 day_target = datetime.datetime(2020, 3, 10)
316 day_after, day_before = neighbor_days(day_target)
317 for district in [d for d in districts_sorted]:
318    total_target = data[day_target][district]['total']
319    total_before = data[day_before][district]['total']
320    data[day_target][district]['growth'] = total_target - total_before
321
322 # Reconstruct data for 13th of March.
323 day_target = datetime.datetime(2020, 3, 13)
324 day_after, day_before = neighbor_days(day_target)
325 data[day_target] = {}
326 for district in [d for d in districts_sorted]:
327    data[day_target][district] = {}
328    total_after = data[day_after][district]['total']
329    growth_after = data[day_after][district]['growth']
330    total_target = total_after - growth_after
331    data[day_target][district]['total'] = total_target
332    total_before = data[day_before][district]['total']
333    data[day_target][district]['growth'] = total_target - total_before
334
335 dates_sorted = list(data.keys())
336 dates_sorted.sort()
337 dates_sorted.reverse()
338
339 # Apply fixes and ensure integrity of results
340 for date in fixes:
341     for district in fixes[date]:
342         for type_ in fixes[date][district]:
343             data[date][district][type_] = fixes[date][district][type_]
344 for date in dates_sorted:
345     if date in fixes:
346        continue
347     for district in [d for d in districts_sorted if not d=='sum']:
348         prev_date = date - datetime.timedelta(days=1)
349         if prev_date not in dates_sorted:
350            if prev_date >= date_limit:
351               raise Exception('Dates not contiguous: %s missing', prev_date)
352            else:
353               continue
354         prev_total = data[prev_date][district]['total']
355         cur_total = data[date][district]['total']
356         if cur_total - data[date][district]['growth'] != prev_total:
357             raise Exception('Questionable district infection total in %s/%s' % (district, date))
358     day_sum = 0
359     for district in [d for d in districts_sorted if not d=='sum']:
360        day_sum += data[date][district]['total']
361     if day_sum != data[date]['sum']['total']:
362         raise Exception('Questionable district infection total sum in %s' % date)
363     day_sum = 0
364     for district in [d for d in districts_sorted if not d=='sum']:
365        day_sum += data[date][district]['growth']
366     if day_sum != data[date]['sum']['growth']:
367         raise Exception('Questionable district infection growth sum in %s' % date)
368
369 # Final output.
370 print(' '*10, ' '.join(['%3s' % d for d in districts_sorted]))
371 for date in dates_sorted:
372     growths = []
373     for d in districts_sorted:
374         growths += [data[date][d]['growth']]
375     print(date.strftime('%Y-%m-%d'), ' '.join(['%3s' % g for g in growths]))