简体   繁体   English

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

[英]html scraping for td element using cheerio js and node js

I have many html files with the below structure. 我有许多具有以下结构的html文件。 I need to get the values 'GET' and ' http://localhost:5601/app/sense ' from the below. 我需要从下面获取值'GET'和' http:// localhost:5601 / app / sense '。 but they are not exact same values in the all the documents, it be post, put or delete. 但是它们在所有文档中都是不完全相同的值,无论是发布,放置还是删除。 but the html structure is same. 但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>

Any suggestion on how to do this with cheerio ? 关于如何用cheerio做到这一点的任何建议? I am trying to parse through the HTML table searching for the method and URL values in td element but I no luck. 我正在尝试通过HTML表解析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());
            });
        });

    }
});

You have to target each TD and get the text, it has no value 您必须定位每个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();

        });

    }
});

Use .eq and .find methods to find your values https://cheerio.js.org/ 使用.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());
       });
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM