Skip to content

Instantly share code, notes, and snippets.

@jgomo3
Created May 17, 2013 21:12
Show Gist options
  • Save jgomo3/5602002 to your computer and use it in GitHub Desktop.
Save jgomo3/5602002 to your computer and use it in GitHub Desktop.
Un borrador de cómo puede analizarse la página del CNE con los resultados electorales con HTMLParser y obtener la parte de los resultados.
class ResultadosParser(HTMLParser):
def __init__(self):
self.estamos_en_el_div = False
self.tds = 0
self.candidato = {} # Un dict vacio
self.resultados = []
def handle_startag(self, tag, args): #
dict_args = dict(args)
if tag == "div" and "id" in dict_args.keys() and dict_args["id"] == "tablaResultados":
self.estamos_en_el_div = True
if self.estamos_en_el_div and tag == "tr" and "class" in dict_args.keys() and dict_args["class"] == "tbsubtotalrow":
self.estamos_viendo_un_candidato = True
if self.estamos_viendo_un_candidato and tag == "td" and ...:
self.tds += 1 # Si empieza en cero, entonces con el primer
# encuentro con el td, sube a 1.
def handle_data(self, data):
if self.tds == 2:
self.segundo_td(data)
elif self.tds == 3:
self.tercero_td(data)
elif self.tds == 4:
self.cuarto_td(data)
def segundo_td(self, data):
self.candidato["nombre"] = self.data
def tercer_td(self, tag, args):
self.candidato["total"] = self.data
def cuarto_td(self, tag, args):
self.candidato["porcentaje"] = self.data
self.resultados.append(self.candidato) # Añadimos el candidato a la lista
def handle_endtag(self, tag, args):
# Bueno, aquí es el mantemiento
if es el div:
self.estamos_en_el_div = False
elif es el tr:
self.estamos_viendo_un_candidato = False
elif es el td:
# creo que mejor reseteamos aquí el contador
self.tds = 0 # Reseteamos el contador
class FichaTecnicaParser(HTMLParser):
def __init__(self):
pass
def handle_endtag(self):
pass
def handle_startag(self):
pass
def handle_data(self):
pass
def generar_reporte_cne_elec_pres_2013(doc):
# lo que dijiste
# luego
el_xml = dame_el_xml(cne_reporte_parser.resultados)
el_otro_xml_el_de_la_ficha_tecnica = dame_el_xml(cne_ficha_tecnica_parser.ficha)
# Bonito, estructurado y estoy reutilizando la función
# dame_el_xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment