Cómo raspar sitios web con Python y BeautifulSoup

Hay más información en Internet de la que cualquier ser humano puede absorber en su vida. Lo que necesita no es acceso a esa información, sino una forma escalable de recopilarla, organizarla y analizarla.

Necesitas web scraping.

El web scraping extrae automáticamente los datos y los presenta en un formato que pueda entender fácilmente. En este tutorial, nos centraremos en sus aplicaciones en el mercado financiero, pero el web scraping se puede utilizar en una amplia variedad de situaciones.

Si es un inversionista ávido, obtener precios de cierre todos los días puede ser un problema, especialmente cuando la información que necesita se encuentra en varias páginas web. Facilitaremos la extracción de datos mediante la creación de un raspador web para recuperar los índices bursátiles automáticamente de Internet.

Empezando

Vamos a utilizar Python como nuestro lenguaje de extracción, junto con una biblioteca simple y poderosa, BeautifulSoup.

  • Para los usuarios de Mac, Python está preinstalado en OS X. Abra Terminal y escriba python --version. Debería ver que su versión de Python es 2.7.x.
  • Para los usuarios de Windows, instale Python a través del sitio web oficial.

A continuación, necesitamos obtener la biblioteca BeautifulSoup usando pipuna herramienta de administración de paquetes para Python.

En la terminal, escriba:

easy_install pip pip install BeautifulSoup4

Nota : Si no puede ejecutar la línea de comando anterior, intente agregar sudodelante de cada línea.

Los basicos

Antes de comenzar a saltar al código, comprendamos los conceptos básicos de HTML y algunas reglas del raspado.

Etiquetas HTML

Si ya comprende las etiquetas HTML, no dude en omitir esta parte.

First Scraping

Hello World

Esta es la sintaxis básica de una página web HTML. Cada sirve un bloque dentro de la página web:

1 .: Los documentos HTML deben comenzar con una declaración de tipo.

2. El documento HTML se encuentra entre y .

3. La declaración de meta y script del documento HTML está entre y .

4. La parte visible del documento HTML se encuentra entre las etiquetas y .

5. Los títulos de título se definen con el

Original text


mediante

etiquetas.

6. Los párrafos se definen con el

Other useful tags include for hyperlinks,

for tables, for table rows, and
para columnas de tabla.

Además, las etiquetas HTML a veces vienen con atributos ido class. El idatributo especifica una identificación única para una etiqueta HTML y el valor debe ser único dentro del documento HTML. El classatributo se utiliza para definir estilos iguales para etiquetas HTML con la misma clase. Podemos hacer uso de estos identificadores y clases para ayudarnos a localizar los datos que queremos.

Para obtener más información sobre etiquetas HTML, id y clase, consulte los tutoriales de W3Schools.

Reglas de raspado

  1. Debe consultar los Términos y condiciones de un sitio web antes de rasparlo. Tenga cuidado de leer las declaraciones sobre el uso legal de datos. Por lo general, los datos que extrae no deben utilizarse con fines comerciales.
  2. No solicite datos del sitio web de manera demasiado agresiva con su programa (también conocido como spam), ya que esto puede dañar el sitio web. Asegúrese de que su programa se comporte de manera razonable (es decir, actúe como un ser humano). Una solicitud de una página web por segundo es una buena práctica.
  3. El diseño de un sitio web puede cambiar de vez en cuando, así que asegúrese de volver a visitar el sitio y reescribir su código según sea necesario.

Inspeccionando la página

Tomemos como ejemplo una página del sitio web de Bloomberg Quote.

Como alguien que sigue el mercado de valores, nos gustaría obtener el nombre del índice (S&P 500) y su precio de esta página. Primero, haga clic derecho y abra el inspector de su navegador para inspeccionar la página web.

Intente colocar el cursor sobre el precio y debería poder ver un cuadro azul que lo rodea. Si hace clic en él, se seleccionará el HTML relacionado en la consola del navegador.

En el resultado, podemos ver que el precio está dentro de algunos niveles de etiquetas HTML, que es .

Del mismo modo, si se desplaza y hace clic en el nombre "Índice S&P 500", está dentro y

.

Ahora conocemos la ubicación única de nuestros datos con la ayuda de classetiquetas.

Ir al código

Ahora que sabemos dónde están nuestros datos, podemos comenzar a codificar nuestro raspador web. ¡Abra su editor de texto ahora!

Primero, necesitamos importar todas las bibliotecas que vamos a usar.

# import libraries import urllib2 from bs4 import BeautifulSoup

A continuación, declare una variable para la URL de la página.

# specify the url quote_page = ‘//www.bloomberg.com/quote/SPX:IND'

Luego, use Python urllib2 para obtener la página HTML de la URL declarada.

# query the website and return the html to the variable ‘page’ page = urllib2.urlopen(quote_page)

Finalmente, analice la página en formato BeautifulSoup para que podamos usar BeautifulSoup para trabajar en ella.

# parse the html using beautiful soup and store in variable `soup` soup = BeautifulSoup(page, ‘html.parser’)

Now we have a variable, soup, containing the HTML of the page. Here’s where we can start coding the part that extracts the data.

Remember the unique layers of our data? BeautifulSoup can help us get into these layers and extract the content with find(). In this case, since the HTML class name is unique on this page, we can simply query .

# Take out the of name and get its value name_box = soup.find(‘h1’, attrs={‘class’: ‘name’})

After we have the tag, we can get the data by getting its text.

name = name_box.text.strip() # strip() is used to remove starting and trailing print name

Similarly, we can get the price too.

# get the index price price_box = soup.find(‘div’, attrs={‘class’:’price’}) price = price_box.text print price

When you run the program, you should be able to see that it prints out the current price of the S&P 500 Index.

Export to Excel CSV

Now that we have the data, it is time to save it. The Excel Comma Separated Format is a nice choice. It can be opened in Excel so you can see the data and process it easily.

But first, we have to import the Python csv module and the datetime module to get the record date. Insert these lines to your code in the import section.

import csv from datetime import datetime

At the bottom of your code, add the code for writing data to a csv file.

# open a csv file with append, so old data will not be erased with open(‘index.csv’, ‘a’) as csv_file: writer = csv.writer(csv_file) writer.writerow([name, price, datetime.now()])

Now if you run your program, you should able to export an index.csv file, which you can then open with Excel, where you should see a line of data.

So if you run this program everyday, you will be able to easily get the S&P 500 Index price without rummaging through the website!

Going Further (Advanced uses)

Multiple Indices

So scraping one index is not enough for you, right? We can try to extract multiple indices at the same time.

First, modify the quote_page into an array of URLs.

quote_page = [‘//www.bloomberg.com/quote/SPX:IND', ‘//www.bloomberg.com/quote/CCMP:IND']

Then we change the data extraction code into a for loop, which will process the URLs one by one and store all the data into a variable data in tuples.

# for loop data = [] for pg in quote_page: # query the website and return the html to the variable ‘page’ page = urllib2.urlopen(pg) # parse the html using beautiful soap and store in variable `soup` soup = BeautifulSoup(page, ‘html.parser’) # Take out the of name and get its value name_box = soup.find(‘h1’, attrs={‘class’: ‘name’}) name = name_box.text.strip() # strip() is used to remove starting and trailing # get the index price price_box = soup.find(‘div’, attrs={‘class’:’price’}) price = price_box.text # save the data in tuple data.append((name, price))

Also, modify the saving section to save data row by row.

# open a csv file with append, so old data will not be erased with open(‘index.csv’, ‘a’) as csv_file: writer = csv.writer(csv_file) # The for loop for name, price in data: writer.writerow([name, price, datetime.now()])

Rerun the program and you should be able to extract two indices at the same time!

Advanced Scraping Techniques

BeautifulSoup is simple and great for small-scale web scraping. But if you are interested in scraping data at a larger scale, you should consider using these other alternatives:

  1. Scrapy, a powerful python scraping framework
  2. Try to integrate your code with some public APIs. The efficiency of data retrieval is much higher than scraping webpages. For example, take a look at Facebook Graph API, which can help you get hidden data which is not shown on Facebook webpages.
  3. Consider using a database backend like MySQL to store your data when it gets too large.

Adopt the DRY Method

DRY stands for “Don’t Repeat Yourself”, try to automate your everyday tasks like this person. Some other fun projects to consider might be keeping track of your Facebook friends’ active time (with their consent of course), or grabbing a list of topics in a forum and trying out natural language processing (which is a hot topic for Artificial Intelligence right now)!

If you have any questions, please feel free to leave a comment below.

References

//www.gregreda.com/2013/03/03/web-scraping-101-with-python/

//www.analyticsvidhya.com/blog/2015/10/beginner-guide-web-scraping-beautiful-soup-python/

This article was originally published on Altitude Labs’ blog and was written by our software engineer, Leonard Mok. Altitude Labs is a software agency that specializes in personalized, mobile-first React apps.