Ahora que ya tenemos las dependencias en el proyecto, veremos cómo usar Cheerio y Puppeteer juntos para crear un scraper web. Al combinar estas dos herramientas, puedes crear un scraper que sea rápido y potente, ¡así que empecemos!
Crea un archivo llamado `scrape.js` y pega el siguiente código en él:
const puppeteer = require('puppeteer');
const cheerio = require('cheerio');
async function scrape() {
// Launch a headless Chrome browser
const browser = await puppeteer.launch();
// Create a new page
const page = await browser.newPage();
// Navigate to the website you want to scrape
await page.goto('https://arstechnica.com/tech-policy/2023/01/musk-led-twitter-faces-another-lawsuit-alleging-it-failed-to-pay-bills/');
// Wait for the page to load
await page.waitForSelector('h1');
// Extract the HTML of the page
const html = await page.evaluate(() => document.body.innerHTML);
// Use Cheerio to parse the HTML
const $ = cheerio.load(html);
// Extract the title, cover image, and paragraph using Cheerio's syntax
const title = $('h1').text();
const paragraph = $('.article-content p:first-of-type').text()
const coverImage = $('figure img').attr('src');
// Display the data we scraped
console.log({
title,
paragraph,
coverImage
});
// Close the browser
await browser.close();
}
scrape();
Puedes ejecutar el código utilizando el comando node scrape.js. El resultado debería mostrar el título del artículo y la URL de la imagen de portada, y debería tener este aspecto:
{
title: 'Lawsuit: Twitter failed to pay $136,000 in rent at San Francisco office tower',
paragraph: 'The Elon Musk-owned Twitter is facing another lawsuit alleging that it failed to pay its bills.',
coverImage: 'https://cdn.arstechnica.net/wp-content/uploads/2023/01/getty-musk-twitter-800x533.jpg'
}