Ejemplo n.º 1
0
    def analize(self,url):
        try: 
            html = urlopen(url)
        except HTTPError as e:
            print(e)
        except URLError:
            print("Servidor no encontrado")
        else:        
            content = html.read().decode('utf-8', 'ignore')
            res = BeautifulSoup(content,"html.parser")
            info = res.find("div",{"id":"publicacionInfo"})
            if (info is None):
                print("NO hay datos de este boletín")
                return False

            numero = int(info.span.getText().split()[1]) 
            # obtener el año. 
            info = res.find("span",{"id":"DOGData"})
            temp = info.getText().split()
            year = int(temp[len(temp)-1])
            mes = self.meses.index(temp[len(temp)-3]) + 1
            dia = int(temp[len(temp)-5])
            fecha = date(year,mes,dia)

            if  (self.checkBulletinExists(self.bulletin,fecha) == True):
                print ("Ya he encontrado datos")
                return True
                
            self.beginAnalysis(fecha)
            #self.setAnalysisState("DOGA",fecha,"INICIADO")
            sections = res.findAll("div",{"id":re.compile('secciones*')})
            for section in sections:
                lines = section.findAll("li")
                for line in lines:
                    if (line.a is not None):
                        noticia = Noticia()
                        noticia.bulletin = self.bulletin
                        noticia.bulletin_year = year
                        noticia.bulletin_no = numero
                        noticia.bulletin_date = fecha
                        noticia.seccion   = ""
                        noticia.organismo = line.findPrevious('p',{'class':'dog-toc-organismo'}).getText()
                        noticia.organo    = ""  #li.span.getText()
                        noticia.servicio  = ""        
                        noticia.newname = line.a.getText()
                        noticia.url = "https://www.xunta.gal" + line.a['href'] 
                        self.normalizar(noticia)
                        pseccion =  line.findPrevious('p',{'class':'dog-toc-nivel-2'})
                        if (pseccion is not None):                                
                            if (pseccion.getText() == 'c) Outros anuncios'):
                                noticia.seccion = 'SECCIÓN NON OFICIAL'
                        if (self.isNotificable(noticia.newname)):
                            noticia.notify = 1
                        noticia.fav = 0
                        noticia.readed = 0
                        noticia.created_at = datetime.now()
                        noticia.updated_at = datetime.now()
                        noticia.imprimir()
                        noticia.save()
Ejemplo n.º 2
0
    def analize(self, url):
        try:
            print("Dentro de analize")
            print(url)
            html = urlopen(url)
        except HTTPError as e:
            print(e)
        except URLError as u:
            print("Servidor depo no encontrado " + url)
            print(u)
        else:
            content = html.read().decode('utf-8', 'ignore')
            res = BeautifulSoup(content, "html.parser")
            strnumero = res.find("h2", {"class": "numero"})

            if (strnumero is None):
                print("No existe boletín para este día")
                return False

            numero = int(strnumero.getText().split()[2])
            info = res.find("span", {"class": "fecha"}).getText().split()
            year = int(info[len(info) - 4])
            mes = self.meses.index(
                info[len(info) - 6]) + 1  # El array comienza en 0
            dia = int(info[len(info) - 8])
            fecha = date(year, mes, dia)

            if (self.checkNumber(year, numero, "BOPPO")):
                return True

            self.beginAnalysis(fecha)
            self.setAnalysisState("BOPPO", fecha, "INICIADO")

            grupo = res.findAll("ul", {"class": "listadoSumario"})

            for tag in grupo:
                organismo = tag.findPrevious('p', {"class": "Org"}).getText()
                seccion = tag.findPrevious('h4', {"class": "tit"}).getText()
                tmp = tag.fetchPreviousSiblings()[0]

                # Busco los elementos anteriores
                lis = tag.findAll("li")
                for li in lis:
                    noticia = Noticia()
                    noticia.bulletin = "BOPPO"
                    noticia.bulletin_year = year
                    noticia.bulletin_no = numero
                    noticia.bulletin_date = fecha
                    noticia.created_at = datetime.now()
                    noticia.updated_at = datetime.now()
                    noticia.seccion = seccion
                    noticia.organismo = organismo
                    noticia.organo = li.span.getText()
                    noticia.servicio = ""
                    noticia.organization = li.span.getText()
                    noticia.newname = li.p.getText()

                    if (tmp.get("class")[0] == "inst"):
                        noticia.organo = tmp.getText()

                    if (self.isNotificable(noticia.newname)):
                        noticia.notify = 1

                    noticia.url = "https://boppo.depo.gal" + li.a['href']
                    self.normalizar(noticia)
                    noticia.imprimir()
                    noticia.save()
            # LLegados aquí, ha finalizado el análisis
            self.setAnalysisState("BOPPO", fecha, "FINALIZADO")
Ejemplo n.º 3
0
    def analize(self, url):
        try:
            html = urlopen(url)
        except HTTPError as e:
            print(e)
        except URLError as u:
            print("Servidor depo no encontrado " + url)
            print(u)
        else:
            content = html.read().decode('utf-8', 'ignore')
            res = BeautifulSoup(content, "html.parser")

            # Vamos a por el número:
            grupo_codigo = res.find('div',
                                    {"class": "field--name-field-ail-codigo"})
            numero = int(
                grupo_codigo.find('div', {'class', 'field__item'}).getText())
            grupo_codigo = res.find(
                'div',
                {'class', 'field--name-field-ail-bop-fecha-publicacion'})
            sfecha = grupo_codigo.find('div', {
                'class': 'field__item'
            }).getText().split()
            dia = int(sfecha[1])
            mes = self.meses.index(sfecha[3].lower()) + 1
            anio = int(sfecha[5])
            fecha = date(anio, mes, dia)

            if (self.checkNumber(anio, numero, "BOPLU")):
                return True
            self.beginAnalysis(fecha)
            self.setAnalysisState("BOPLU", fecha, "INICIADO")

            div = res.find("div",
                           {"class": "field--name-field-ail-bop-contenido"})
            lista = div.find("ul")
            secciones = lista.children
            for seccion in secciones:
                if hasattr(seccion, 'strong'):
                    seccion_nombre = seccion.strong.getText()

                if (not hasattr(seccion, 'children')):
                    continue
                lista = seccion.find("ul")
                if (lista is not None):
                    organismos = lista.findChildren("li", recursive=False)
                    for organismo in organismos:
                        noticias = organismo.find("ul")
                        if ((organismo.strong is None) or (noticias is None)):
                            noticia = Noticia()
                            noticia.bulletin = "BOPLU"
                            noticia.bulletin_year = anio
                            noticia.bulletin_no = numero
                            noticia.bulletin_date = fecha
                            noticia.created_at = datetime.now()
                            noticia.updated_at = datetime.now()
                            noticia.seccion = "OTROS"
                            noticia.organismo = seccion_nombre
                            noticia.organo = ""
                            noticia.servicio = ""
                            noticia.organization = ""
                            if (organismo.a is not None):
                                noticia.newname = organismo.a.getText()
                                noticia.url = "http://deputacionlugo.gal" + organismo.a[
                                    'href']
                            else:
                                print("Ha habido una incidencia")
                                noticia.newname = "INCIDENCIA: "

                            if (self.isNotificable(noticia.newname)):
                                noticia.notify = 1

                            self.normalizar(noticia)
                            noticia.imprimir()
                            noticia.save()
                        else:
                            noticias = organismo.ul.findChildren("li")
                            for n in noticias:
                                noticia = Noticia()
                                noticia.bulletin = "BOPLU"
                                noticia.bulletin_year = anio
                                noticia.bulletin_no = numero
                                noticia.bulletin_date = fecha
                                noticia.created_at = datetime.now()
                                noticia.updated_at = datetime.now()
                                noticia.seccion = seccion_nombre
                                noticia.organismo = organismo.strong.getText()
                                noticia.organo = ""
                                noticia.servicio = ""
                                noticia.organization = ""
                                noticia.newname = n.a.getText()

                                if (self.isNotificable(noticia.newname)):
                                    noticia.notify = 1

                                noticia.url = "http://deputacionlugo.gal" + n.a[
                                    'href']
                                self.normalizar(noticia)
                                noticia.imprimir()
                                noticia.save()
                else:
                    print("Lista vacía")
            self.setAnalysisState("BOPLU", fecha, "FINALIZADO")
Ejemplo n.º 4
0
    def analize(self, url):
        try:
            html = urlopen(url)
        except HTTPError as e:
            print(e)
        except URLError as u:
            print("Servidor BOE no encontrado " + url)
            print(u)
        else:
            print("Iniciando Análisis del BOE...")
            content = html.read().decode('utf-8', 'ignore')
            res = BeautifulSoup(content, "html.parser")

            cabecera = res.find('div', {'class': "tituloSumario"})
            partes = cabecera.getText().split()
            dia = int(partes[5])
            mes = self.meses.index(partes[7]) + 1
            ano = int(partes[9][:-1])
            numero = partes[11]
            fecha = date(ano, mes, dia)

            #<div class="solapasMultiplesBOES"><ul>
            #    <li class="current"><abbr title="Número">Núm.</abbr> 89</li>
            #    <li><a href="index.php?d=88"><abbr title="Número">Núm.</abbr> 88</a></li>
            #    </ul>
            #</div>
            multiple = res.find('div', {'class': 'solapasMultiplesBOES'})
            if multiple is not None:
                print("Encontrado día múltiple")
                numero = int(
                    multiple.find('li', {
                        'class': 'current'
                    }).getText().split(" ")[1])
                ano = int(partes[9])

                if "/index.php?d=" not in url:
                    otros = multiple.findAll("li", {'class': None})
                    for o in otros:
                        newurl = url + o.a['href']
                        print(newurl)
                        if newurl not in self.urls_visited:
                            self.urls.append(newurl)

            fecha = date(ano, mes, dia)

            # Comprobamos si ya existe
            #if (self.checkBulletinExists(self.bulletin,fecha) == True):
            if (self.checkNumber(ano, numero, self.bulletin) == True):
                print("Ya he encontrado datos")
                return True

            self.beginAnalysis(fecha)
            self.setAnalysisState(self.bulletin, fecha, "INICIADO")

            noticias = res.findAll("li", {"class": "dispo"})

            i = 1
            for n in noticias:
                print("Noticia número: " + str(i))
                noticia = Noticia()
                noticia.bulletin = self.bulletin
                noticia.bulletin_year = ano
                noticia.bulletin_no = numero
                noticia.bulletin_date = fecha
                noticia.created_at = datetime.now()
                noticia.updated_at = datetime.now()
                noticia.newname = n.p.getText()
                noticia.seccion = ""
                if (self.isNotificable(noticia.newname)):
                    noticia.notify = 1
                noticia.url = "https://www.boe.es" + n.div.ul.li.a['href']

                # Encontrar los antecesores:
                h3 = n.findPrevious('h3')
                if (h3 is not None):
                    noticia.seccion = h3.getText()

                h4 = n.findPrevious('h4')
                if (h4 is not None):
                    noticia.organismo = h4.getText()

                h5 = n.findPrevious('h5')
                if (h5 is not None):
                    h4b = h5.findPrevious('h4')
                    if (h4b.getText() == h4.getText()):
                        noticia.organo = h5.getText()

                # self.normalizar(noticia)
                noticia.imprimir()
                noticia.save()

                i += 1

            self.setAnalysisState(self.bulletin, fecha, "FINALIZADO")
Ejemplo n.º 5
0
    def analize(self):
        url = 'https://bop.depourense.es/portal/cambioBoletin.do'
        fechas = self.urlGenerator()
        #for f in fechas:
        #    print (url + "   ." + f + ".")

        for fecha in fechas:
            post_params = {'fechaInput': fecha}
            response = requests.post(url, data=post_params)
            res = BeautifulSoup(response.text, 'html.parser')

            texto = res.find("div", {"class": "resumenSumario"})
            if (texto is None):
                print("No se ha encontrado boletín")
                return False

            sumario = texto.getText().split()
            numero = int(sumario[4])
            year = int(sumario[11])
            mes = self.meses.index(sumario[9]) + 1  # El array comienza en 0
            dia = int(sumario[7])
            fecha = date(year, mes, dia)
            self.beginAnalysis(fecha)
            self.setAnalysisState("BOPOU", fecha, "INICIADO")
            v_url = "https://bop.depourense.es/portal/" + res.find(
                "a", {"class": "enlacePdfS"})['href']

            if (self.checkNumber(year, numero, "BOPOU") == False):
                grupo = res.findAll("td", {"class": "textoS", "width": "90%"})

                for elemento in grupo:
                    noticia = Noticia()
                    noticia.newname = elemento.getText().strip()
                    noticia.organismo = elemento.findPrevious(
                        'span', {
                            "class": "tituloS"
                        }).getText()
                    noticia.seccion = elemento.findPrevious(
                        'span', {
                            "class": "seccionS"
                        }).getText()
                    noticia.bulletin = "BOPOU"
                    noticia.bulletin_year = year
                    noticia.bulletin_no = numero
                    noticia.bulletin_date = fecha
                    noticia.servicio = ""
                    noticia.url = v_url
                    noticia.created_at = datetime.now()
                    noticia.updated_at = datetime.now()
                    if (self.isNotificable(noticia.newname)):
                        noticia.notify = 1

                    self.normalizar(noticia)
                    noticia.imprimir()
                    noticia.save()
            else:
                print("Paso al siguiente")

            self.setAnalysisState("BOPOU", fecha, "FINALIZADO")
            print("Esperando")
            time.sleep(5)
            print("Reanudando")
Ejemplo n.º 6
0
    def analize(self, url):
        try:
            html = urlopen(url)
        except HTTPError as e:
            print(e)
        except URLError as u:
            print("Servidor depo no encontrado " + url)
            print(u)
        else:
            content = html.read().decode('utf-8', 'ignore')
            res = BeautifulSoup(content, "html.parser")

            s_info = res.find("div", {"id": "infoBoletin"})
            if (s_info is None):
                print("No se ha encontrado boletín")
                return False

            info = s_info.find("a").getText()
            cachos = info.split()
            numero = int(cachos[4])
            dia = int(cachos[7])
            mes = self.meses.index(cachos[9]) + 1
            ano = int(cachos[11])
            fecha = date(ano, mes, dia)

            if (self.checkNumber(ano, numero, "BOPCO")):
                return True  # Ya existen.

            self.beginAnalysis(fecha)
            self.setAnalysisState("BOPCO", fecha, "INICIADO")

            anuncios = res.findAll("div", {"class": "bloqueAnuncio"})
            for anuncio in anuncios:
                noticia = Noticia()
                noticia.bulletin = "BOPCO"
                noticia.bulletin_year = ano
                noticia.bulletin_no = numero
                noticia.bulletin_date = fecha

                if (anuncio.find("h2")):
                    noticia.organismo = anuncio.find("h2").getText()
                    noticia.organo = anuncio.find("h3").getText()
                    servi = anuncio.find("h4")
                    if (servi is not None):
                        noticia.servicio = anuncio.find("h4").getText()
                else:
                    tmp = anuncio.find("h3")
                    if (tmp is not None):
                        noticia.organismo = anuncio.find("h3").getText()
                    else:
                        noticia.organismo = "OTROS"

                    if (anuncio.find("h4")):
                        noticia.organo = anuncio.find("h4").getText()

                    noticia.servicio = ""
                noticia.seccion = anuncio.findPrevious(
                    'h1', {
                        "class": "administracion"
                    }).getText()

                resumen = anuncio.find("p", {"class": "resumenSumario"})
                noticia.url = "https://bop.dacoruna.gal/bopportal/publicado/" + str(
                    ano) + "/" + str(mes) + "/" + str(
                        dia) + "/" + resumen.select("a")[0]['href']
                noticia.newname = resumen.select("a")[0].getText().strip(
                ) + " - " + resumen.select("a")[1].getText().strip()
                # la notificación hay que comprobarla
                if (self.isNotificable(noticia.newname)):
                    noticia.notify = 1
                noticia.fav = 0
                noticia.readed = 0
                noticia.created_at = datetime.now()
                noticia.updated_at = datetime.now()
                noticia.imprimir()
                noticia.save()
            self.setAnalysisState("BOPCO", fecha, "FINALIZADO")