Introducción a Web Scraping en JavaScript
El web scraping es una de las cosas más interesantes en el mundo de la codificación.
¿Qué es el web scraping?
¿Por qué existe?
Averigüemos las respuestas.
¿Qué es el web scraping?
El web scraping es un proceso automático.ated task to extract data from websites.
There are many applications of web scraping. Extracting the prices of products and comparing them with different Plataformas de comercio electrónico. Obtener una cotización diaria de la web. Construyendo su propio motor de búsqueda como Google, Yahoo, etc., la lista continúa.
You can do more than you think with web scraping. Once you get to know how to extract the data from websites, then you can do whatever lo que quieras con los datos.
The program which extracts the data from websites is called a web scraper. You are going to learn to write web scrapers en JavaScript.
El raspado web consta principalmente de dos partes.
- Getting the data using request libraries and a headless browser.
- Parsing the data to extract the exact information that we want from the data.
Sin más preámbulos, comencemos.
Configuración del proyecto
Supongo que tiene Node instalado, si no, consulte el Guía de instalación de NodeJS.
Vamos a utilizar los paquetes node-fetch
y cheerio
para raspado web en JavaScript. Configuremos el proyecto con npm para que funcione con un third-paquete de fiesta.
Veamos rápidamente los pasos para completar nuestra configuración.
- Create un directorio llamado
web_scraping
y navegarate a la misma. - Ejecuta el comando
npm init
para inicializar el proyecto. - Responda todas las preguntas según su preferencia.
- Ahora, instale los paquetes usando el comando
npm install node-fetch cheerio
Veamos los destellos de los paquetes instalados.
búsqueda de nodo
El paquete node-fetch
trae el window.fetch
al entorno de node js. Ayuda a realizar las solicitudes HTTP y obtener los datos sin procesar.
¡hasta la vista
El paquete ¡hasta la vista is used to parse and extract the information that is necessary from the raw data.
Dos paquetes node-fetch
y cheerio
son lo suficientemente buenos para web scraping en JavaScript. No veremos todos los métodos que proporcionan los paquetes. Veremos el flujo de web scraping y los métodos más útiles en ese flujo.
Aprenderá a raspar web haciéndolo. Entonces, vayamos al trabajo.
Lista de la Copa Mundial de Cricket de raspado
Aquí, en esta sección, haremos un raspado web real.
What are we extracting?
Por el título de la sección, creo que lo adivinarías fácilmente. Sí, ¿qué?atever you are thinking is correct. Let’s extract all cricket world cup winners and runner-ups till now.
- Create un archivo llamado
extract_cricket_world_cups_list.js
en el proyecto. - Usaremos el Wikipedia Copa del mundo de críquet página para obtener la información deseada.
- Primero, obtenga los datos sin procesar usando el
node-fetch
paquete. - El siguiente código obtiene los datos sin procesar de la página de Wikipedia anterior.
const fetch = require("node-fetch");
// function to get the raw data
const getRawData = (URL) => {
return fetch(URL)
.then((response) => response.text())
.then((data) => {
return data;
});
};
// URL for data
const URL = "https://en.wikipedia.org/wiki/Cricket_World_Cup";
// start of the program
const getCricketWorldCupsList = async () => {
const cricketWorldCupRawData = await getRawData(URL);
console.log(cricketWorldCupRawData);
};
// invoking the main function
getCricketWorldCupsList();
We got the raw data from the URL. Now, it’s time to extract the information that we need from the raw data. Let’s use the package cheerio to extract the data.
Extracting data that involves HTML tags with cheerio is a cakewalk. Before getting into the actual data, let’s see some sample data parsing using cheerio
.
- Analizar los datos HTML usando
cheerio.load
el método.
const parsedSampleData = cheerio.load(
`<div id="container"><p id="title">I'm title</p></div>`
);
- We have parsed the above HTML code. How to extract el
p
etiquetar contenido de él? Es lo mismo que los selectores en la manipulación DOM de JavaScript.
console.log(parsedSampleData("#title").text());
Puede seleccionar las etiquetas que desee. Puede consultar diferentes métodos de la sitio web oficial de cheerio.
- Ahora es el momento de extract the world cup list. To extract the information, we need to know the HTML tags that information lies on the page. Go to the página de Wikipedia de la copa mundial de cricket y inspect la página para obtener información de etiquetas HTML.
Aquí está el código completo.
const fetch = require("node-fetch");
const cheerio = require("cheerio");
// function to get the raw data
const getRawData = (URL) => {
return fetch(URL)
.then((response) => response.text())
.then((data) => {
return data;
});
};
// URL for data
const URL = "https://en.wikipedia.org/wiki/Cricket_World_Cup";
// start of the program
const getCricketWorldCupsList = async () => {
const cricketWorldCupRawData = await getRawData(URL);
// parsing the data
const parsedCricketWorldCupData = cheerio.load(cricketWorldCupRawData);
// extracting the table data
const worldCupsDataTable = parsedCricketWorldCupData("table.wikitable")[0]
.children[1].children;
console.log("Year --- Winner --- Runner");
worldCupsDataTable.forEach((row) => {
// extracting `td` tags
if (row.name === "tr") {
let year = null,
winner = null,
runner = null;
const columns = row.children.filter((column) => column.name === "td");
// extracting year
const yearColumn = columns[0];
if (yearColumn) {
year = yearColumn.children[0];
if (year) {
year = year.children[0].data;
}
}
// extracting winner
const winnerColumn = columns[3];
if (winnerColumn) {
winner = winnerColumn.children[1];
if (winner) {
winner = winner.children[0].data;
}
}
// extracting runner
const runnerColumn = columns[5];
if (runnerColumn) {
runner = runnerColumn.children[1];
if (runner) {
runner = runner.children[0].data;
}
}
if (year && winner && runner) {
console.log(`${year} --- ${winner} --- ${runner}`);
}
}
});
};
// invoking the main function
getCricketWorldCupsList();
Y aquí están los datos extraídos.
Year --- Winner --- Runner
1975 --- West Indies --- Australia
1979 --- West Indies --- England
1983 --- India --- West Indies
1987 --- Australia --- England
1992 --- Pakistan --- England
1996 --- Sri Lanka --- Australia
1999 --- Australia --- Pakistan
2003 --- Australia --- India
2007 --- Australia --- Sri Lanka
2011 --- India --- Sri Lanka
2015 --- Australia --- New Zealand
2019 --- England --- New Zealand
Genial 😎, ¿está en eso?
Plantilla de raspadoate
Getting the raw data from the URL is common in every web scraping project. The only part that changes is extracting the data as per the requirement. You can try the below code as a template.
const fetch = require("node-fetch");
const cheerio = require("cheerio");
const fs = require("fs");
// function to get the raw data
const getRawData = (URL) => {
return fetch(URL)
.then((response) => response.text())
.then((data) => {
return data;
});
};
// URL for data
const URL = "https://example.com/";
// start of the program
const scrapeData = async () => {
const rawData = await getRawData(URL);
// parsing the data
const parsedData = cheerio.load(rawData);
console.log(parsedData);
// write code to extract the data
// here
// ...
// ...
};
// invoking the main function
scrapeData();
Para Concluir
Ha aprendido a raspar una página web. Ahora es tu turno de practicar la codificación.
También te sugiero que revises los populares marcos de web scraping para explorar y soluciones de raspado web basadas en la nube.
Codificación feliz 🙂