Utilicé cheerio por primera vez hoy Esta es una versión simplificada de la fuente html que quiero.
<div id="country-table"> <!-- div duplicate cause style --> <div> <div> <table> <tbody> <tr> <td>1</td> <td>USA</td> <td>1.6</td> <td>75.8</td> <td>132,000</td> </tr> <tr> <td>2</td> <td>INDIA</td> <td>12123</td> <td>1322</td> <td>123213</td> </tr> <tr> <td>3</td> <td>BRAZIL</td> <td>3123</td> <td>213123</td> <td>134</td> </tr> <tr> <!-- and more... --> </tbody> </table> </div> </div> </div>y traté de esto:
const axios = require("axios").default; const cheerio = require("cheerio").default; axios.get("https://coronaboard.kr").then((html) => { const arr = []; const $ = cheerio.load(html.data, { xml: true, xmlMode: true }); const data = $("#country-table>div>div>table>tbody").each((index, item) => { arr.push(item); }); console.log(arr); });Quiero poner información en td en tr. ex){número:x,nombre:EE. UU.,confirmado:x,y más...}
Si alguien sabe como hacerlo por favor que me responda!
Si desea extraer los datos de la tabla, esto le ayudará. Sigue los comentarios para ayudarte a entender cómo funciona.
var $ = cheerio.load(html.data); // targets the specific table with a selector var html_table = $('#country-table>div>div>table'); // gets table cell values; loops through all tr rows var table_data = html_table.find('tr').map(function() { // gets the cells value for the row; loops through each cell and returns an array of values var cells = $(this).find('td').map(function() {return $(this).text().trim();}).toArray(); // returns an array of the cell data collected return [cells]; }).toArray(); // output table data console.log('table_data', table_data);