| 10 | |
| 11 | |
| 12 | class CepTracker(): |
| 13 | |
| 14 | def __init__(self): |
| 15 | self.log_path = 'log.yaml' |
| 16 | self._config_log_file() |
| 17 | self.logger = logging.getLogger(__name__) |
| 18 | |
| 19 | self.url = 'http://m.correios.com.br/movel/buscaCepConfirma.do' |
| 20 | |
| 21 | def _config_log_file(self): |
| 22 | with open(self.log_path, 'rt') as f: |
| 23 | config = yaml.load(f.read()) |
| 24 | logging.config.dictConfig(config) |
| 25 | |
| 26 | def _request(self, cep): |
| 27 | response = requests.post(self.url, data={ |
| 28 | 'cepEntrada': cep, |
| 29 | 'tipoCep': '', |
| 30 | 'cepTemp': '', |
| 31 | 'metodo': 'buscarCep' |
| 32 | }) |
| 33 | try: |
| 34 | response.raise_for_status() |
| 35 | except requests.exceptions.HTTPError as ex: |
| 36 | logging.error('Erro request site Correios', exc_info=True) |
| 37 | raise ex |
| 38 | return response.text |
| 39 | |
| 40 | def _get_infos_(self, cep): |
| 41 | from lxml.html import fromstring |
| 42 | response = self._request(cep) |
| 43 | html = fromstring(response) |
| 44 | registro_csspattern = '.caixacampobranco, .caixacampoazul' |
| 45 | registros = html.cssselect(registro_csspattern) |
| 46 | |
| 47 | resultado = [] |
| 48 | for item in registros: |
| 49 | item_csspattern = '.resposta, .respostadestaque' |
| 50 | resultado.append([a.text for a in item.cssselect(item_csspattern)]) |
| 51 | |
| 52 | return resultado |
| 53 | |
| 54 | def track(self, cep): |
| 55 | itens = self._get_infos_(cep) |
| 56 | result = [] |
| 57 | |
| 58 | for item in itens: |
| 59 | |
| 60 | data = dict() |
| 61 | data["v_date"] = datetime.now() |
| 62 | |
| 63 | for label, value in zip(item[0::2], item[1::2]): |
| 64 | |
| 65 | label = label.lower().strip(' :') |
| 66 | value = re.sub('\s+', ' ', value.strip()) |
| 67 | |
| 68 | if 'localidade' in label: |
| 69 | cidade, estado = value.split('/', 1) |
no outgoing calls
no test coverage detected