Web Scraping Course for SEO – Class 8

Get metatag description

On each page we will obtain the description included in the metatag <meta content = ‘…’ name = ‘description’ />

 

# -*- coding: iso-8859-15 -*-

# Proyecto Web Scraping para SEO con Python
# Clase 8: Obtener metatag description# webscrap8
import urllib
import re

url_sitio = “https://evginformatica.blogspot.com/”
url_inicio=url_sitio
lista_enlaces = []
titulos = []
descripciones = []
def buscar_enlaces(posicion,busqueda):
   
    url = lista_enlaces[posicion]
   
    htmluni = urllib.urlopen(url).read()
    html=urllib.unquote(htmluni).decode(“utf-8”)
    #buscar <title>
    if titulos[posicion]==“”:
        titulo = re.findall(“<title>.+</title>”, html)
        if titulo<>[]:
            titulo_esp=titulo[0]
            titulos[posicion]=titulo_esp[7:-8]
   
    #buscar descripcion
    #<meta content=’…’ name=’description’/>    if descripciones[posicion]==“”:
        desc = re.findall(“<meta content=.+name=’description’/>”, html)
        if desc<>[]:
            desc_esp=desc[0]
            descripciones[posicion]=desc_esp[15:-22]
 
    #buscar enlaces href
    enlaces = re.findall(busqueda, html)
    for enlace in enlaces:
   
        #quitar href=’ y quitar comilla final
        enlace2 = enlace[6:-1]
   
        #enlaces excluidos
        #/search
        # o que contienen #
        # solo paginas .html
        anadir=True
        if enlace2.find(“.html”)<0:
            anadir=False
       
        if enlace2.find(“/search”)>0:
            anadir=False
       
        if enlace2.find(“#”)>0:
            anadir=False
       
        if enlace2 in lista_enlaces:
            anadir=False
           
        if anadir:
            lista_enlaces.append(enlace2)
            titulos.append(“”)
            descripciones.append(“”)

def web_scrapin():
   
    print “— Enlaces internos —“
   
    lista_enlaces.append(url_inicio)
    titulos.append(“”)
    descripciones.append(“”)
    posicion = 0
   
    while True:
        #print “— “+lista_enlaces[posicion]
       
        busqueda = “href='”+url_sitio+“.+?'”
        buscar_enlaces(posicion,busqueda)
        busqueda = ‘href=”‘+url_sitio+‘.+?”‘
        buscar_enlaces(posicion,busqueda)
       
           
        posicion = posicion+1
        #pruebas
        #if posicion >= 2:
        #    break
       
        if posicion >= len(lista_enlaces):
            break
           
    i=1
    for lenlace in lista_enlaces:
        print str(i)+” “+lenlace       
        print ”     Titulo: “+titulos[i-1]
        print ”     Descripcion: “+descripciones[i-1]
        i=i+1
   



if __name__ == “__main__”:  
    web_scrapin()

On each page we find we look for the description with the regular expression <meta content =. + Name = ‘description’ /> and we store them in the descriptions list.

Leave a Reply

Your email address will not be published. Required fields are marked *