home · contact · privacy
Grow scraper date range.
[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    # This one has no press release but can be reconstructed from
92    # the neighbour ones.
93    datetime.datetime(2020, 3, 13): {
94         'CW': {'growth': 16, 'total': 47},
95         'FK': {'growth': 8, 'total': 22},
96         'Li': {'growth': 2, 'total': 8},
97         'MH': {'growth': 1, 'total': 4},
98         'Mi': {'growth': 9, 'total': 29},
99         'Ne': {'growth': 6, 'total': 16},
100         'Pa': {'growth': 11, 'total': 26},
101         'Re': {'growth': 0, 'total': 11},
102         'Sp': {'growth': 1, 'total': 9},
103         'SZ': {'growth': 0, 'total': 20},
104         'TS': {'growth': 1, 'total': 17},
105         'TK': {'growth': 3, 'total': 7},
106         'sum': {'growth': 58, 'total': 216}
107    }
108 }
109 fixes = {
110    # Here the official total is 215, while the summation of district
111    # numbers only adds up to 125 – pretty much looks like a mere
112    # transposition of digits.
113    datetime.datetime(2020, 3, 27): {
114        'sum': {
115            'growth': 125
116        }
117    },
118    # Here the official total is 1937, while the summation of district
119    # numbers only adds up to 1917; furthermore, the original value for
120    # SZ is 118 (+18), which makes no sense, as the day before is
121    # 120 (+15) and the day after is 147 (+15).  The following is a
122    # compromise to keep as many surrounding numbers stable as possible.
123    datetime.datetime(2020, 3, 26): {
124        'SZ': {
125            'growth': 12
126        },
127        'sum': {
128            'growth': 286
129        }
130    },
131    # Here the official total is 220, while the summation of district
132    # numbers adds up to 228 – looks like someone misread an 8 as a 0.
133    datetime.datetime(2020, 3, 25): {
134        'sum': {
135            'growth': 220
136        }
137    },
138 }
139
140 # Scan navigation bar for maximum pagination value.
141 url = url_prefix + pm_dir
142 with urllib.request.urlopen(url) as response:
143    html = response.read()
144 soup = bs4.BeautifulSoup(html, 'html.parser')
145 max_page=0
146 for link in soup.find_all('a'):
147     href = link['href']
148     if str.startswith(href, pm_nav_path):
149         max_test = int(href.split('=')[1])
150         max_page = max_test if max_test > max_page else max_page
151
152 # Scan paginated press release links for daily Corona number briefing links.
153 day_urls = []
154 for i in range(max_page):
155     url = url_prefix + pm_nav_path + str(i + 1)
156     with urllib.request.urlopen(url) as response:
157         html = response.read()
158     soup = bs4.BeautifulSoup(html, 'html.parser')
159     for link in soup.find_all('a'):
160         if (not link.string) or\
161            (not link.string.startswith('Coronavirus: Derzeit') and
162             not link.string.startswith('Coronavirus in Berlin: Bestätigte Fälle')):
163             continue
164         day_urls += [link['href']]
165
166 # Collect infection data.
167 first_run = True
168 districts_sorted = []
169 # TODO: Push limit further back (might need more data fixes for that).
170 date_limit = datetime.datetime(2020, 3, 12)
171 for path in day_urls:
172     url = url_prefix + path
173     with urllib.request.urlopen(url) as response:
174         html = response.read()
175     soup = bs4.BeautifulSoup(html, 'html.parser')
176     date_title = soup.find('div', class_='pressnumber')
177     m = re.search('[0-9]+\\.[0-9]+\\.[0-9]+', date_title.string)
178     date_formatted = m.group(0)
179     date = datetime.datetime.strptime(date_formatted , '%d.%m.%Y')
180     if date_limit > date:
181         break
182     # On that day, two press releases were released, for that and the prev day.
183     if date == datetime.datetime(2020, 3, 15) and date in data:
184        date = datetime.datetime(2020, 3, 14)
185     # From here on, press releases describe numbers from prev day.
186     if date <= datetime.datetime(2020, 3, 13):
187        date = date - datetime.timedelta(days=1)
188     table = soup.find('table')
189     if table is None and date in data:
190         continue
191     data[date] = {}
192     for tr in [tr for tr in table.children if type(tr) == bs4.element.Tag][1:]:
193         printable_tds = []
194         for td in [td for td in tr.children if type(td) == bs4.element.Tag][:2]:
195             printable_string = ' '.join([s for s in td.strings])
196             printable_tds += [printable_string.strip()]
197         district_long = printable_tds[0]
198         district_short = [k for k in abbrevs if district_long in abbrevs[k]][0]
199         if first_run:
200             districts_sorted += [district_short]
201         split_char = ' '
202         if not split_char in printable_tds[1]:
203             split_char = '('
204         total_str, growth_str = printable_tds[1].split(split_char)
205         growth = int(growth_str.replace('(', '').replace(')', '').replace('+', ''))
206         total = int(total_str.replace('.', ''))
207         data[date][district_short] = {'growth': growth, 'total': total}
208     first_run = False
209 dates_sorted = list(data.keys())
210 dates_sorted.sort()
211 dates_sorted.reverse()
212
213 # Apply fixes and ensure integrity of results
214 for date in fixes:
215     for district in fixes[date]:
216         for type_ in fixes[date][district]:
217             data[date][district][type_] = fixes[date][district][type_]
218 for date in dates_sorted:
219     if date in fixes:
220        continue
221     for district in [d for d in districts_sorted if not d=='sum']:
222         prev_date = date - datetime.timedelta(days=1)
223         if prev_date not in dates_sorted:
224            if prev_date >= date_limit:
225               raise Exception('Dates not contiguous: %s missing', prev_date)
226            else:
227               continue
228         prev_total = data[prev_date][district]['total']
229         cur_total = data[date][district]['total']
230         if cur_total - data[date][district]['growth'] != prev_total:
231             raise Exception('Questionable district infection total in %s/%s' % (district, date))
232     day_sum = 0
233     for district in [d for d in districts_sorted if not d=='sum']:
234        day_sum += data[date][district]['total']
235     if day_sum != data[date]['sum']['total']:
236         raise Exception('Questionable district infection total sum in %s' % date)
237     day_sum = 0
238     for district in [d for d in districts_sorted if not d=='sum']:
239        day_sum += data[date][district]['growth']
240     if day_sum != data[date]['sum']['growth']:
241         raise Exception('Questionable district infection growth sum in %s' % date)
242
243 # Final output.
244 print(' '*10, ' '.join(['%3s' % d for d in districts_sorted]))
245 for date in dates_sorted:
246     growths = []
247     for d in districts_sorted:
248         growths += [data[date][d]['growth']]
249     print(date.strftime('%Y-%m-%d'), ' '.join(['%3s' % g for g in growths]))