Naposledy aktivní 6 hours ago

Revize ec6901e73c60dc29ac1996dfcf46f43d3d7e65cb

extract_cnes.py Raw
1#!/usr/bin/env python3
2"""Extract CNES hospital table from DATASUS."""
3
4import csv
5import sys
6import requests
7from bs4 import BeautifulSoup
8
9URL = "https://cnes2.datasus.gov.br/Mod_Ind_Unidade_Listar.asp?VTipo=05&VListar=1&VEstado=31&VMun=&VSubUni=&VComp=201412"
10OUTPUT = "cnes_hospitais.csv"
11
12
13def fetch(url: str) -> BeautifulSoup:
14 headers = {
15 "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"
16 }
17 r = requests.get(url, headers=headers, timeout=30)
18 r.encoding = "iso-8859-1"
19 return BeautifulSoup(r.text, "html.parser")
20
21
22def extract_table(soup: BeautifulSoup) -> tuple[list[str], list[list[str]]]:
23 # Target the bordered data table (not layout tables)
24 table = soup.find("table", {"border": "1"})
25 if not table:
26 raise ValueError("Tabela não encontrada na página.")
27
28 rows = table.find_all("tr")
29 if not rows:
30 raise ValueError("Nenhuma linha encontrada na tabela.")
31
32 headers = [th.get_text(strip=True) for th in rows[0].find_all("td")]
33 data = []
34 for row in rows[1:]:
35 cells = [td.get_text(strip=True) for td in row.find_all("td")]
36 if cells:
37 data.append(cells)
38
39 return headers, data
40
41
42def save_csv(headers: list[str], data: list[list[str]], path: str) -> None:
43 with open(path, "w", newline="", encoding="utf-8") as f:
44 writer = csv.writer(f)
45 writer.writerow(headers)
46 writer.writerows(data)
47
48
49def main() -> None:
50 print(f"Buscando: {URL}")
51 soup = fetch(URL)
52
53 headers, data = extract_table(soup)
54 print(f"Colunas: {headers}")
55 print(f"Linhas: {len(data)}")
56
57 save_csv(headers, data, OUTPUT)
58 print(f"Salvo em: {OUTPUT}")
59
60
61if __name__ == "__main__":
62 try:
63 main()
64 except Exception as e:
65 print(f"Erro: {e}", file=sys.stderr)
66 sys.exit(1)
67