Estoy tratando de extraer datos de un sitio web de los CDC .
Estoy usando cheerio.js para obtener los datos y copio el selector HTML en mi código, así:
const listItems = $('#tab1_content > div > table > tbody > tr:nth-child(1) > td:nth-child(3)');Sin embargo, cuando ejecuto el programa, solo obtengo una matriz en blanco. ¿Cómo es esto posible? Estoy copiando el selector de HTML palabra por palabra en mi código, entonces, ¿por qué no funciona? Aquí hay un video corto que muestra el problema: https://youtu.be/a3lqnO_D4pM
Aquí está mi código completo, junto con un enlace donde puede ejecutar el código:
const axios = require("axios"); const cheerio = require("cheerio"); const fs = require("fs"); // URL of the page we want to scrape const url = "https://nccd.cdc.gov/DHDSPAtlas/reports.aspx?geographyType=county&state=CO&themeId=2&filterIds=5,1,3,6,7&filterOptions=1,1,1,1,1"; // Async function which scrapes the data async function scrapeData() { try { // Fetch HTML of the page we want to scrape const { data } = await axios.get(url); // Load HTML we fetched in the previous line const $ = cheerio.load(data); // Select all the list items in plainlist class const listItems = $('#tab1_content > div > table > tbody > tr:nth-child(1) > td:nth-child(3)'); // Stores data in array const dataArray = []; // Use .each method to loop through the elements listItems.each((idx, el) => { // Object holding data const dataObject = { name: ""}; // Store the textcontent in the above object dataObject.name = $(el).text(); // Populate array with data dataArray.push(dataObject); }); // Log array to the console console.dir(dataArray); } catch (err) { console.error(err); } } // Invoke the above function scrapeData();Ejecute el código aquí: https://replit.com/@STCollier/Web-Scraping#index.js
Gracias por cualquier ayuda.