You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Node.js+Cheerio循环提取HTML表格tr下的td生成新表格?

解决方案

你需要遍历表格tbody下的每个<tr>元素,再提取每个<tr>内的<td>文本内容,最后拼接成完整的HTML表格。以下是修改后的完整代码:

import fetch from "node-fetch";
import cheerio from "cheerio";
import fs from 'fs'; // 如果需要将表格写入文件,导入fs模块

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

function getData(html) {
  const $ = cheerio.load(html);
  
  // 提取表格表头(thead中的th)
  const tableHeaders = [];
  $("#block-system-main > div > table > thead th").each(function() {
    tableHeaders.push($(this).text().trim());
  });

  // 遍历tbody中的每一行tr,提取td内容
  $("#block-system-main > div > table > tbody tr").each(function() {
    const rowData = [];
    // 遍历当前tr下的所有td
    $(this).find("td").each(function() {
      // 去除文本前后的空格和换行,存入行数据数组
      rowData.push($(this).text().trim());
    });
    scrapedData.push(rowData);
  });

  // 生成HTML表格字符串
  let htmlTable = "<table border='1' cellpadding='8' cellspacing='0'>";
  
  // 添加表头部分
  htmlTable += "<thead><tr>";
  tableHeaders.forEach(header => {
    htmlTable += `<th>${header}</th>`;
  });
  htmlTable += "</tr></thead>";

  // 添加表格主体内容
  htmlTable += "<tbody>";
  scrapedData.forEach(row => {
    htmlTable += "<tr>";
    row.forEach(cell => {
      htmlTable += `<td>${cell}</td>`;
    });
    htmlTable += "</tr>";
  });
  htmlTable += "</tbody></table>";

  // 打印生成的HTML表格
  console.log(htmlTable);

  // 可选:将HTML表格写入本地文件
  fs.writeFileSync('brvm-stocks-table.html', htmlTable);
  console.log("HTML表格已保存到brvm-stocks-table.html");
}

关键修改说明

  1. 选择器调整:将原代码中遍历<tbody>的逻辑,改为遍历<tbody>下的所有<tr>元素,确保能拿到每一行数据。
  2. 提取单元格数据:对每个<tr>,使用find("td")获取所有单元格,通过trim()清理文本中的冗余空格和换行,保证数据整洁。
  3. 生成HTML表格:
    • 先提取表头的<th>内容,构建表格头部;
    • 再遍历收集到的行数据,逐行生成<tr>和<td>标签;
    • 添加border、cellpadding等属性优化表格显示效果。
  4. 可选文件写入:通过fs模块将生成的HTML表格保存到本地文件,方便直接查看。

内容的提问来源于stack exchange,提问作者Koffi Frederic Sessie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:45:40