Skip to content

Instantly share code, notes, and snippets.

@JuniorPolegato
Created April 13, 2015 15:49
Show Gist options
  • Save JuniorPolegato/62b1f2e9458cd0d19819 to your computer and use it in GitHub Desktop.
Save JuniorPolegato/62b1f2e9458cd0d19819 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import pytz
import pole
cf = pole.util.cf
# Importando o html para PoleXML
root = pole.xml.importar(open('nfe.html').read().strip(), html=True)
# Os dados pertinente estão seguindo as tags <html><body><form>, no 3º <div>
dados = root.html.body.form.div(3)
# Navegando entre os filhos e mostrando o html dentro deles
filhos = dados('') # 12 filhos
for f in range(1, filhos + 1): # loop para mostrar cada filho
filho = dados('', f)
print '-' * 50, f, '-', filho._XML__nome, '-' * 50
print repr(dados('', f))
# Trantando o 1º filho (table)
filho = dados('', 1)
# Olhando o HTML, dentro deste filho (<table>), 1º tr, 1º td, 2º span, 1º span
chave_str = str(filho.tr.td.span(2).span)
chave = pole.util.somente_digitos(chave_str)
print 'Chave de acesso:', chave_str
print 'Chave de acesso:', chave
# Olhando o HTML, dentro deste filho (<table>), 1º tr, 2º td, 2º span, 1º span
num_nfe = str(filho.tr.td(2).span(2).span)
# Olhando o HTML, dentro deste filho (<table>), 1º tr, 3º td, 2º span, 1º span
versao_nfe = str(filho.tr.td(3).span(2).span)
print 'NFe: %s (versão %s)' % (num_nfe, versao_nfe)
# Trantando o 3º filho (<div>) - o segundo é apenas um <br>
filho = dados('', 3)
# Linha da tabela dentro do 1º fieldset
linha = filho.fieldset.table.tr
modelo = str(linha.td.span)
serie = str(linha.td(2).span)
numero = str(linha.td(3).span)
emissao = cf(str(linha.td(4).span), datetime.datetime)[0]
saida = cf(str(linha.td(5).span), datetime.datetime)[0]
valor_total = cf(str(linha.td(6).span), float)[0]
print modelo, serie, numero, emissao, saida, valor_total
# Linha da tabela dentro do 2º fieldset
linha = filho.fieldset(2).table.tr
cnpj_emitente = pole.util.somente_digitos(str(linha.td.span))
nome_razao_social_emitente = str(linha.td(2).span)
ie_emitente = pole.util.somente_digitos(str(linha.td(3).span))
uf_emitente = str(linha.td(4).span)
print cnpj_emitente, nome_razao_social_emitente, ie_emitente, uf_emitente
# Linha da tabela dentro do 3º fieldset
# ... por aí vai ...
# Trantando o 5º filho (<div>) - o 4º é apenas um <script>
# ... por aí vai ...
def dh_nfe(data_hora_tz):
tz = pytz.timezone(open('/etc/timezone').read().strip())
dh = tz.localize(data_hora_tz).strftime('%Y-%m-%dT%H:%M:%S%z')
dh = dh[:-2] + ':' + dh[-2:]
return dh
# Montando a NF-e em XML
root_nfe = pole.xml.XML()
root_nfe.nfeProc['xmlns'] = "http://www.portalfiscal.inf.br/nfe"
root_nfe.nfeProc['versao'] = "3.10"
root_nfe.nfeProc.NFe['xmlns'] = "http://www.portalfiscal.inf.br/nfe"
root_nfe.nfeProc.NFe.infNFe['Id'] = 'NFe' + chave
root_nfe.nfeProc.NFe.infNFe['versao'] = "3.10"
# Identificação, onde x precisa encontrar o valor no html
x = 'procurar'
ide = root_nfe.nfeProc.NFe.infNFe.ide
ide.cUF = chave[:2]
ide.cNF = chave[-9:-1]
ide.natOp = x
ide.indPag = x
ide.mod = modelo
ide.serie = serie
ide.nNF = num_nfe
ide.dhEmi = dh_nfe(emissao)
ide.dhSaiEnt = dh_nfe(saida)
ide.tpNF = x
ide.idDest = x
ide.cMunFG = x
ide.tpImp = x
ide.tpEmis = x
ide.cDV = chave[-1]
ide.tpAmb = 1
ide.finNFe = x
ide.indFinal = x
ide.indPres = x
ide.procEmi = x
ide.verProc = x
# E assim vai com os outros campos da NF-e
emit = root_nfe.nfeProc.NFe.infNFe.emit
emit.CNPJ = x
emit.xNome = x
emit.enderEmit = x
emit.enderEmit.xLgr = x
emit.enderEmit.nro = x
emit.enderEmit.xCpl = x
emit.enderEmit.xBairro = x
emit.enderEmit.cMun = x
emit.enderEmit.xMun = x
emit.enderEmit.UF = x
emit.enderEmit.CEP = x
emit.enderEmit.cPais = x
emit.enderEmit.xPais = x
emit.IE = x
emit.CRT = x
dest = root_nfe.nfeProc.NFe.infNFe.dest
dest.CPF = x
dest.xNome = x
dest.enderDest = x
dest.enderDest.xLgr = x
dest.enderDest.nro = x
dest.enderDest.xCpl = x
dest.enderDest.xBairro = x
dest.enderDest.cMun = x
dest.enderDest.xMun = x
dest.enderDest.UF = x
dest.enderDest.CEP = x
dest.enderDest.cPais = x
dest.enderDest.xPais = x
dest.enderDest.fone = x
dest.indIEDest = x
dest.email = x
# Vai seguindo montando a nfeProc contendo NFe e procNFe, contudo não terá
# o certificado de quem assinou a NFe
# Salva a NF-e em XML
with open(chave + '-nfe.xml', 'w') as arquivo:
arquivo.write(pole.xml.serializar(root_nfe))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment