首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用cheerio解析html

使用cheerio解析html
EN

Stack Overflow用户
提问于 2021-09-26 14:53:02
回答 1查看 53关注 0票数 1

今天我第一次使用cheerio,这是我想要的html源代码的简化版本。

代码语言:javascript
复制
<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>

我试着这样做:

代码语言:javascript
复制
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);
});

我想把td中的信息放到tr中。例如){编号:X,名称:美国,确认:X,以及更多...}

如果有人知道怎么做,请回答我!

EN

回答 1

Stack Overflow用户

发布于 2021-11-12 14:29:17

如果您想要从表中提取数据,那么这将会有所帮助。按照注释来帮助您理解它是如何工作的。

代码语言:javascript
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69336082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档