Last active
August 29, 2015 14:08
-
-
Save rafaelhdr/befd372e8af8f0716261 to your computer and use it in GitHub Desktop.
Get Brazilizian Postal Code (CEP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Added on http://www.rafaelhdr.com.br/blog/python/pegar-cep-do-site-dos-correios-em-python at 25/10/2014 | |
# | |
# This is a simple function to get data at brazilian correios | |
# It searches at http://www.buscacep.correios.com.br/ and return as a dict the | |
# information retrieved. | |
# | |
# Before use it, you need install the following libs: | |
# pip install beautifulsoup4 | |
# pip install requests | |
import requests | |
from bs4 import BeautifulSoup | |
import re | |
def get_brcep(cep): | |
# Getting data | |
session = requests.session() | |
data = {'relaxation': cep, | |
'TipoCep': 'ALL', | |
'semelhante': 'N', | |
'cfm': '1', | |
'Metodo': 'listaLogradouro', | |
'TipoConsulta': 'relaxation', | |
'StartRow': '1', | |
'EndRow': '10', | |
} | |
r = session.post("http://www.buscacep.correios.com.br/servicos/dnec/consultaEnderecoAction.do", data) | |
content = r.content | |
# Parsing | |
soup = BeautifulSoup(content) | |
items = soup.find_all('table')[2].find_all('td') | |
# Returning data | |
return { | |
'address': re.sub(' - .*', '', items[0].string), | |
'district': items[1].string, | |
'city': items[2].string, | |
'state': items[3].string, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment