-
Notifications
You must be signed in to change notification settings - Fork 0
/
cidades.py
63 lines (41 loc) · 1.39 KB
/
cidades.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
import contextlib
import csv
import os
import shutil
import urllib.request
import requests_html
import xlrd
url = 'https://www.ibge.gov.br/geociencias/organizacao-do-territorio/estrutura-territorial/15761-areas-dos-municipios.html'
def find_xls_link(response):
links = response.html.find('#acesso-ao-produto a')
xls_link = next(link for link in links if link.text == 'xls')
assert xls_link
return xls_link.attrs['href']
def ftp_download(url):
_, filename = os.path.split(url)
with contextlib.closing(urllib.request.urlopen(url)) as r:
with open(filename, 'wb') as f:
shutil.copyfileobj(r, f)
return filename
def csv_from_excel(filename):
wb = xlrd.open_workbook(filename)
for sheet in wb.sheets():
with open(f'data/{sheet.name}.csv', 'w') as f:
wr = csv.writer(f, quoting=csv.QUOTE_ALL)
for rownum in range(sheet.nrows):
row = sheet.row_values(rownum)
if not row[0]:
continue
try:
row[0] = int(row[0])
except ValueError:
pass
wr.writerow(row)
def main():
session = requests_html.HTMLSession()
response = session.get(url)
xls_link = find_xls_link(response)
filename = ftp_download(xls_link)
csv_from_excel(filename)
if __name__ == '__main__':
main()