Tutorial de Web Scraping Python: cómo extraer datos de un sitio web

Python es un hermoso lenguaje para codificar. Tiene un gran ecosistema de paquetes, hay mucho menos ruido del que encontrarás en otros lenguajes y es muy fácil de usar.

Python se usa para varias cosas, desde el análisis de datos hasta la programación del servidor. Y un caso de uso interesante de Python es Web Scraping.

En este artículo, cubriremos cómo usar Python para web scraping. También trabajaremos con una guía práctica completa del aula a medida que avancemos.

Nota: Estaremos raspando una página web que yo aloje, para que podamos aprender a rasparla de manera segura. Muchas empresas no permiten raspar en sus sitios web, por lo que esta es una buena forma de aprender. Solo asegúrese de verificar antes de raspar.

Introducción al aula de Web Scraping

Si desea codificar, puede usar este aula de codedamn gratuitaque consta de varios laboratorios que le ayudarán a aprender sobre el raspado web. Este será un ejercicio de aprendizaje práctico sobre codedamn, similar a cómo se aprende en freeCodeCamp.

En este aula, utilizará esta página para probar el raspado web: //codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/

Este aula consta de 7 laboratorios, y resolverá un laboratorio en cada parte de esta publicación de blog. Usaremos Python 3.8 + BeautifulSoup 4 para web scraping.

Parte 1: carga de páginas web con 'solicitud'

Este es el enlace a este laboratorio.

El requestsmódulo le permite enviar solicitudes HTTP usando Python.

La solicitud HTTP devuelve un objeto de respuesta con todos los datos de respuesta (contenido, codificación, estado, etc.). Un ejemplo de cómo obtener el HTML de una página:

import requests res = requests.get('//codedamn.com') print(res.text) print(res.status_code)

Pasar requisitos:

  • Obtenga el contenido de la siguiente URL mediante el requestsmódulo: //codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/
  • Almacene la respuesta de texto (como se muestra arriba) en una variable llamada txt
  • Almacene el código de estado (como se muestra arriba) en una variable llamada status
  • Imprimir txty statususar la printfunción

Una vez que comprenda lo que está sucediendo en el código anterior, es bastante sencillo aprobar este laboratorio. Aquí está la solución para este laboratorio:

import requests # Make a request to //codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/ # Store the result in 'res' variable res = requests.get( '//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/') txt = res.text status = res.status_code print(txt, status) # print the result

Pasemos a la parte 2 ahora, donde podrá construir más sobre su código existente.

Parte 2: Extraer el título con BeautifulSoup

Este es el enlace a este laboratorio.

En toda esta clase, usará una biblioteca llamada BeautifulSoupen Python para hacer web scraping. Algunas características que hacen de BeautifulSoup una solución poderosa son:

  1. Proporciona muchos métodos simples y modismos Pythonic para navegar, buscar y modificar un árbol DOM. No se necesita mucho código para escribir una aplicación
  2. Beautiful Soup se encuentra en la parte superior de los analizadores de Python populares como lxml y html5lib, lo que le permite probar diferentes estrategias de análisis o cambiar la velocidad por flexibilidad.

Básicamente, BeautifulSoup puede analizar cualquier cosa en la web que le des.

Aquí hay un ejemplo simple de BeautifulSoup:

from bs4 import BeautifulSoup page = requests.get("//codedamn.com") soup = BeautifulSoup(page.content, 'html.parser') title = soup.title.text # gets you the text of the (...)

Pasar requisitos:

  • Utilice el requestspaquete para obtener el título de la URL: //codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/
  • Use BeautifulSoup para almacenar el título de esta página en una variable llamada page_title

Mirando el ejemplo anterior, puede ver que una vez que alimentamos el page.contentinterior de BeautifulSoup, puede comenzar a trabajar con el árbol DOM analizado de una manera muy pitónica. La solución para el laboratorio sería:

import requests from bs4 import BeautifulSoup # Make a request to //codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/ page = requests.get( "//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/") soup = BeautifulSoup(page.content, 'html.parser') # Extract title of page page_title = soup.title.text # print the result print(page_title)

Este también fue un laboratorio simple en el que tuvimos que cambiar la URL e imprimir el título de la página. Este código pasaría el laboratorio.

Parte 3: Cuerpo y cabeza en sopa

Este es el enlace a este laboratorio.

En el último laboratorio, vio cómo puede extraer el titlede la página. Es igualmente fácil extraer ciertas secciones también.

También vio que debe llamar .texta estos para obtener la cadena, pero puede imprimirlos sin llamar .texttambién, y le dará el marcado completo. Intente ejecutar el siguiente ejemplo:

import requests from bs4 import BeautifulSoup # Make a request page = requests.get( "//codedamn.com") soup = BeautifulSoup(page.content, 'html.parser') # Extract title of page page_title = soup.title.text # Extract body of page page_body = soup.body # Extract head of page page_head = soup.head # print the result print(page_body, page_head)

Echemos un vistazo a cómo puede extraer bodyy headsecciones de sus páginas.

Pasar requisitos:

  • Repita el experimento con URL: //codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/
  • Almacene el título de la página (sin llamar .text) de la URL en page_title
  • Almacene el contenido del cuerpo (sin llamar .text) de la URL en page_body
  • Almacene el contenido principal (sin llamar .text) de la URL en page_head

Cuando intente imprimir el page_bodyo page_headverá que están impresos como strings. Pero en realidad, cuando print(type page_body)veas que no es una cuerda pero funciona bien.

La solución de este ejemplo sería simple, basada en el código anterior:

import requests from bs4 import BeautifulSoup # Make a request page = requests.get( "//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/") soup = BeautifulSoup(page.content, 'html.parser') # Extract title of page page_title = soup.title # Extract body of page page_body = soup.body # Extract head of page page_head = soup.head # print the result print(page_title, page_head)

Parte 4: seleccione con BeautifulSoup

Este es el enlace a este laboratorio.

Ahora que ha explorado algunas partes de BeautifulSoup, veamos cómo puede seleccionar elementos DOM con los métodos de BeautifulSoup.

Once you have the soup variable (like previous labs), you can work with .select on it which is a CSS selector inside BeautifulSoup. That is, you can reach down the DOM tree just like how you will select elements with CSS. Let's look at an example:

import requests from bs4 import BeautifulSoup # Make a request page = requests.get( "//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/") soup = BeautifulSoup(page.content, 'html.parser') # Extract first 

(...)

text first_h1 = soup.select('h1')[0].text

.select returns a Python list of all the elements. This is why you selected only the first element here with the [0] index.

Passing requirements:

  • Create a variable all_h1_tags. Set it to empty list.
  • Use .select to select all the

    tags and store the text of those h1 inside all_h1_tags list.

  • Create a variable seventh_p_text and store the text of the 7th p element (index 6) inside.

The solution for this lab is:

import requests from bs4 import BeautifulSoup # Make a request page = requests.get( "//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/") soup = BeautifulSoup(page.content, 'html.parser') # Create all_h1_tags as empty list all_h1_tags = [] # Set all_h1_tags to all h1 tags of the soup for element in soup.select('h1'): all_h1_tags.append(element.text) # Create seventh_p_text and set it to 7th p element text of the page seventh_p_text = soup.select('p')[6].text print(all_h1_tags, seventh_p_text) 

Let's keep going.

Part 5: Top items being scraped right now

This is the link to this lab.

Let's go ahead and extract the top items scraped from the URL: //codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/

If you open this page in a new tab, you’ll see some top items. In this lab, your task is to scrape out their names and store them in a list called top_items. You will also extract out the reviews for these items as well.

To pass this challenge, take care of the following things:

  • Use .select to extract the titles. (Hint: one selector for product titles could be a.title)
  • Use .select to extract the review count label for those product titles. (Hint: one selector for reviews could be div.ratings) Note: this is a complete label (i.e. 2 reviews) and not just a number.
  • Create a new dictionary in the format:
info = { "title": 'Asus AsusPro Adv... '.strip(), "review": '2 reviews\n\n\n'.strip() }
  • Note that you are using the strip method to remove any extra newlines/whitespaces you might have in the output. This is important to pass this lab.
  • Append this dictionary in a list called top_items
  • Print this list at the end

There are quite a few tasks to be done in this challenge. Let's take a look at the solution first and understand what is happening:

import requests from bs4 import BeautifulSoup # Make a request page = requests.get( "//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/") soup = BeautifulSoup(page.content, 'html.parser') # Create top_items as empty list top_items = [] # Extract and store in top_items according to instructions on the left products = soup.select('div.thumbnail') for elem in products: title = elem.select('h4 > a.title')[0].text review_label = elem.select('div.ratings')[0].text info = { "title": title.strip(), "review": review_label.strip() } top_items.append(info) print(top_items)

Note that this is only one of the solutions. You can attempt this in a different way too. In this solution:

  1. First of all you select all the div.thumbnail elements which gives you a list of individual products
  2. Then you iterate over them
  3. Because select allows you to chain over itself, you can use select again to get the title.
  4. Note that because you're running inside a loop for div.thumbnail already, the h4 > a.title selector would only give you one result, inside a list. You select that list's 0th element and extract out the text.
  5. Finally you strip any extra whitespace and append it to your list.

Straightforward right?

Part 6: Extracting Links

This is the link to this lab.

So far you have seen how you can extract the text, or rather innerText of elements. Let's now see how you can extract attributes by extracting links from the page.

Here’s an example of how to extract out all the image information from the page:

import requests from bs4 import BeautifulSoup # Make a request page = requests.get( "//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/") soup = BeautifulSoup(page.content, 'html.parser') # Create top_items as empty list image_data = [] # Extract and store in top_items according to instructions on the left images = soup.select('img') for image in images: src = image.get('src') alt = image.get('alt') image_data.append({"src": src, "alt": alt}) print(image_data)

In this lab, your task is to extract the href attribute of links with their text as well. Make sure of the following things:

  • You have to create a list called all_links
  • In this list, store all link dict information. It should be in the following format:
info = { "href": "", "text": "" }
  • Make sure your text is stripped of any whitespace
  • Make sure you check if your .text is None before you call .strip() on it.
  • Store all these dicts in the all_links
  • Print this list at the end

You are extracting the attribute values just like you extract values from a dict, using the get function. Let's take a look at the solution for this lab:

import requests from bs4 import BeautifulSoup # Make a request page = requests.get( "//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/") soup = BeautifulSoup(page.content, 'html.parser') # Create top_items as empty list all_links = [] # Extract and store in top_items according to instructions on the left links = soup.select('a') for ahref in links: text = ahref.text text = text.strip() if text is not None else '' href = ahref.get('href') href = href.strip() if href is not None else '' all_links.append({"href": href, "text": text}) print(all_links) 

Here, you extract the href attribute just like you did in the image case. The only thing you're doing is also checking if it is None. We want to set it to empty string, otherwise we want to strip the whitespace.

Part 7: Generating CSV from data

This is the link to this lab.

Finally, let's understand how you can generate CSV from a set of data. You will create a CSV with the following headings:

  1. Product Name
  2. Price
  3. Description
  4. Reviews
  5. Product Image

These products are located in the div.thumbnail. The CSV boilerplate is given below:

import requests from bs4 import BeautifulSoup import csv # Make a request page = requests.get( "//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/") soup = BeautifulSoup(page.content, 'html.parser') all_products = [] products = soup.select('div.thumbnail') for product in products: # TODO: Work print("Work on product here") keys = all_products[0].keys() with open('products.csv', 'w',) as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(all_products) 

You have to extract data from the website and generate this CSV for the three products.

Passing Requirements:

  • Product Name is the whitespace trimmed version of the name of the item (example - Asus AsusPro Adv..)
  • Price is the whitespace trimmed but full price label of the product (example - $1101.83)
  • The description is the whitespace trimmed version of the product description (example - Asus AsusPro Advanced BU401LA-FA271G Dark Grey, 14", Core i5-4210U, 4GB, 128GB SSD, Win7 Pro)
  • Reviews are the whitespace trimmed version of the product (example - 7 reviews)
  • Product image is the URL (src attribute) of the image for a product (example - /webscraper-python-codedamn-classroom-website/cart2.png)
  • The name of the CSV file should be products.csv and should be stored in the same directory as your script.py file

Let's see the solution to this lab:

import requests from bs4 import BeautifulSoup import csv # Make a request page = requests.get( "//codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/") soup = BeautifulSoup(page.content, 'html.parser') # Create top_items as empty list all_products = [] # Extract and store in top_items according to instructions on the left products = soup.select('div.thumbnail') for product in products: name = product.select('h4 > a')[0].text.strip() description = product.select('p.description')[0].text.strip() price = product.select('h4.price')[0].text.strip() reviews = product.select('div.ratings')[0].text.strip() image = product.select('img')[0].get('src') all_products.append({ "name": name, "description": description, "price": price, "reviews": reviews, "image": image }) keys = all_products[0].keys() with open('products.csv', 'w',) as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(all_products) 

The for block is the most interesting here. You extract all the elements and attributes from what you've learned so far in all the labs.

When you run this code, you end up with a nice CSV file. And that's about all the basics of web scraping with BeautifulSoup!

Conclusion

I hope this interactive classroom from codedamn helped you understand the basics of web scraping with Python.

If you liked this classroom and this blog, tell me about it on my twitter and Instagram. Would love to hear feedback!