forked from turicas/covid19-br
-
Notifications
You must be signed in to change notification settings - Fork 0
/
obitos_spider.py
128 lines (106 loc) · 4.07 KB
/
obitos_spider.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
import datetime
import json
from urllib.parse import urlencode, urljoin
import scrapy
from scrapy.http.cookies import CookieJar
import date_utils
STATES = "AC AL AM AP BA CE DF ES GO MA MG MS MT PA PB PE PI PR RJ RN RO RR RS SC SE SP TO".split()
def qs_to_dict(data):
"""
>>> result = qs_to_dict([("a", 1), ("b", 2)])
>>> expected = {'a': 1, 'b': 2}
>>> result == expected
True
>>> result = qs_to_dict([("b", 0), ("a", 1), ("b", 2)])
>>> expected = {'a': 1, 'b': [0, 2]}
>>> result == expected
True
"""
from collections import defaultdict
new = defaultdict(list)
for key, value in data:
new[key].append(value)
return {key: value if len(value) > 1 else value[0] for key, value in new.items()}
class BaseRegistroCivilSpider(scrapy.Spider):
cookie_jar = CookieJar()
login_url = "https://transparencia.registrocivil.org.br/registral-covid"
start_urls = []
xsrf_token = ""
custom_settings = { "USER_AGENT": "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.44 Safari/537.36", }
def start_requests(self):
yield self.make_login_request()
def make_login_request(self):
return scrapy.Request(
url=self.login_url,
callback=self.parse_login_response,
meta={"dont_cache": True},
)
def make_request(self, *args, **kwargs):
kwargs["headers"] = kwargs.get("headers", {})
kwargs["headers"]["X-XSRF-TOKEN"] = self.xsrf_token
return scrapy.Request(*args, **kwargs)
def start_requests_after_login(self):
for url in self.start_urls:
yield self.make_request(url, callback=self.parse)
def parse_login_response(self, response):
self.cookie_jar.extract_cookies(response, response.request)
self.xsrf_token = next(
c for c in self.cookie_jar if c.name == "XSRF-TOKEN"
).value
for request in self.start_requests_after_login():
yield request
def parse(self):
raise NotImplementedError()
class DeathsSpider(BaseRegistroCivilSpider):
name = "obitos"
registral_url = (
"https://transparencia.registrocivil.org.br/api/covid-covid-registral"
)
causes_map = {
"sars": "SRAG",
"pneumonia": "PNEUMONIA",
"respiratory_failure": "INSUFICIENCIA_RESPIRATORIA",
"septicemia": "SEPTICEMIA",
"indeterminate": "INDETERMINADA",
"others": "OUTRAS",
"covid19": "COVID",
}
def start_requests_after_login(self):
for state in STATES:
for year in [2020, 2019]:
yield self.make_registral_request(
start_date=datetime.date(year, 1, 1),
end_date=datetime.date(year, 12, 31),
state=state,
dont_cache=True,
)
def make_registral_request(self, start_date, end_date, state, dont_cache=False):
data = [
("chart", "chart5"),
("city_id", "all"),
("end_date", str(end_date)),
("places[]", "HOSPITAL"),
("places[]", "DOMICILIO"),
("places[]", "VIA_PUBLICA"),
("places[]", "OUTROS"),
("start_date", str(start_date)),
("state", state),
]
return self.make_request(
url=urljoin(self.registral_url, "?" + urlencode(data)),
headers={"X-XSRF-TOKEN": self.xsrf_token},
callback=self.parse_registral_request,
meta={"row": qs_to_dict(data), "dont_cache": dont_cache},
)
def parse_registral_request(self, response):
state = response.meta["row"]["state"]
data = json.loads(response.body)
for date, chart in data["chart"].items():
row = {"date": date, "state": state}
for cause, portuguese_name in self.causes_map.items():
row[cause] = (
chart[portuguese_name][0]["total"]
if portuguese_name in chart
else None
)
yield row