Save results to file
In this class we will see how we can write the results to a file instead of the console.
To write the results to a file we can proceed in several ways:
. open a file and change print to write
. redirect standard output to a file when running the script
. redirect standard output to open file from python
We will follow the third procedure
# Proyecto Web Scraping para SEO con Python
# Clase 10: Guardar resultados en fichero
# webscrap10
import urllib
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]
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 “— Web Scraping —“
#esto es para indicar que la codificación del fichero es utf-8 #no ascii
reload(sys)
sys.setdefaultencoding(‘utf-8’)
#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()
So that there are no problems with accents, we must indicate that the standard output as the file to open have the UTF-8 encoding.
To indicate that the standard output is UTF-8, you must put it at the beginning
# – * – coding: utf-8 – * –
In the web_scrapin function we change the encoding of the text files from ascii to utf-8 with the lines
reload (sys)
sys.setdefaultencoding (‘utf-8’)
then we open the file and redirect the standard output to that file with
file = open (‘c:\webscrap.txt’, ‘w’)
sys.stdout = file
when we have already written all the information we put the standard output back as it was with
sys.stdout = sys .__ stdout__