Web Scraping Course for SEO – Class 11

Conversion to Python version 3.6

In this class we will convert our program from version 2.7 to version 3.6

 

# Proyecto Web Scraping para SEO con Python
# Clase 11: Conversión a Python versión 3.6
# webscrap11

import urllib.request, urllib.parse, urllib.error
import re
import sys

url_sitio = “https://evginformatica.blogspot.com/”
url_inicio=url_sitio
lista_enlaces = []
titulos = []
descripciones = []

def buscar_enlaces(posicion,busqueda):
 
  url = lista_enlaces[posicion]
 
  htmlbytes = urllib.request.urlopen(url).read()
  html2 = htmlbytes.decode(“utf-8”)
  html = urllib.parse.unquote(html2)


  #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(“— Web Scraping —“)

  #esto es para indicar que la codificación del fichero es utf-8
  #no ascii #reload(sys)
  #sys.setdefaultencoding(‘utf-8’)
  # no es necesario en la version 3.6
  #redirigir salida estandard a fichero
  fichero=open(‘c:\webscrap.txt’, ‘w’)
  sys.stdout=fichero



  print(“— Información del sitio “+url_sitio)
  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

  #volver a poner la salida estandard como estaba
  sys.stdout=sys.__stdout__
  print(“— Fin Web Scraping —“)



if __name__ == “__main__”:  
    web_scrapin()

 

The differences between version 2.7 and 3.6 for this program are

htmlbytes = urllib.request.urlopen (url) .read ()
html2 = htmlbytes.decode (“utf-8”)
html = urllib.parse.unquote (html2)

Change the urlopen function and return a sequence of bytes instead of a string.

The decode function is applied to obtain a string in UTF-8 format

With urllib.parse.unquote the special marks are removed (% 20 …)

The default files are in UTF-8 format

In python 3.6 print is a function not a statement so it has to go in parentheses.

 

Compartir
Publicado por
Enrique Vicente