Parse table from HTML with cheerio in node

Viewed 60

I'm trying to scrape data from this website (https://www.brvm.org/fr/cours-actions/0) using nodejs in visual studio code.

With the code I can get the tr elements but I want to make a loop which will push every children td of a tr to create a table in html.

Below is my code

import fetch from "node-fetch";
import cheerio from "cheerio";

const scrapedData = [];
async function fetchData(url) {
  const response = await fetch(url);
  const data = await response.text();
  /*  console.log(data); */
  getData(data);
}
fetchData("https://www.brvm.org/fr/cours-actions/0");

function getData(html) {
  const $ = cheerio.load(html);
  $("#block-system-main > div > table > tbody", html).each(function () {
    console.log($(this).text());
  });  
}

The table i want to scrape Tr element of my table

How can I create the loop?

1 Answers

You can loop over the rows, then use .find on each row to grab its cells:

import cheerio from "cheerio"; // 1.0.0-rc.12

const parseHTML = html => {
  const $ = cheerio.load(html);
  const sel = "#block-system-main > div > table > tbody tr";
  return [...$(sel)].map(e =>
    [...$(e).find("td")].map(e => $(e).text())
  );
};

(async () => {
  const url = "https://www.brvm.org/fr/cours-actions/0";
  const response = await fetch(url);
  const result = parseHTML(await response.text());
  console.table(result);
})();

See also Scraping all rows from table using cheerio.

Related