html 使用 cheerio js 和 node js 抓取 td 元素

html scraping for td element using cheerio js and node js

我有很多 html 具有以下结构的文件。我需要从下面获取值 'GET' 和 'http://localhost:5601/app/sense'。但它们在所有文档中的值并不完全相同,可能是 post、put 或 delete。但 html 结构相同。

<colgroup>
      <col class="col-lg-1">
      <col class="col-lg-7">
   </colgroup>
   <tbody>
      <tr>
         <td>
            <code>Method</code>
         </td>
         <td>GET</td>
      </tr>
      <tr>
         <td>
            <code>URL Path &amp; Params</code>
         </td>
         <td>http://localhost:5601/app/sense</td>
      </tr>
   </tbody>
</table>

关于如何使用 cheerio 执行此操作的任何建议?我试图通过 HTML table 搜索方法和 td 元素中的 URL 值进行解析,但我没有运气。

glob(__dirname + "/../docs/*/*/*/*/*/*.html", function (er, files) {
    for (var i = 0; i < files.length; i++) {

        fs.readFile(files[i], (err, data) => {
            if (err) throw err;
            $ = cheerio.load(data);
            $('tr').each(function () {
                console.log($('td').val());
            });
        });

    }
});

您必须定位每个 TD 并获取文本,它没有价值

glob(__dirname + "/../docs/*/*/*/*/*/*.html", function (er, files) {
    for (var i = 0; i < files.length; i++) {

        fs.readFile(files[i], (err, data) => {
            if (err) throw err;
            var $ = cheerio.load(data);

            var method = $('tr').eq(0).find('td').eq(1).text();
            var url    = $('tr').eq(1).find('td').eq(1).text();

        });

    }
});

使用 .eq 和 .find 方法查找您的值https://cheerio.js.org/

glob(__dirname + "/../docs/*/*/*/*/*/*.html", function (er, files) {
   for (var i = 0; i < files.length; i++) {

        fs.readFile(files[i], (err, data) => {
          if (err) throw err;
          $ = cheerio.load(data);
          console.log($('tr').eq(0).find('td').eq(1).text());
          console.log($('tr').eq(1).find('td').eq(1).text());
       });
   }
});